1、转字符串类型:String(v)或v.toString()
2、转数字:Number(v)
3、自动转换:连接符+的一方是字符串,则另一方也会被转成字符串;其它算术运算符会把另一方转成数字。
//number to string
var str=String(123);
var str2=String(100*2);
document.write(str,"</br>",str2,"</br>");
num=3.141592627;
str=num.toString();
document.write(str,"</br>");
str=num.toFixed(2);//3.14
document.write(str,"</br>");
str=num.toPrecision(4);//3.142
document.write(str,"</br>");
num/=100;
str=num.toExponential(3);//3.142e-2
document.write(str,"</br>");
//boolean to string
str=String(true);
document.write(str==="true","</br>");
str=false.toString();
document.write(str==="false","</br>");
//Date to string
str=String(Date());
document.write(str,"</br>");
str=Date().toString();
document.write(str,"</br>");
//get year
var date=new Date();
document.write(date.getFullYear(),"year</br>");
//get month
document.write(date.getMonth()+1,"month</br>");
//get date
document.write(date.getDate(),"date</br>");
//get hour
document.write(date.getHours(),"hour</br>");
//get minute
document.write(date.getMinutes(),"minute</br>");
//get second
document.write(date.getSeconds(),"second</br>");
//get millisecond
document.write(date.getMilliseconds(),"millisecond</br>");
//get all milliseconds
document.write(date.getTime(),"time</br>");
//get day in week
var day=date.getDay();
switch(day){
case 0:
document.write("sunday</br>");
break;
case 1:
document.write("monday</br>");
break;
case 2:
document.write("Tuesday</br>");
break;
case 3:
document.write("Wednsday</br>");
break;
case 4:
document.write("Thursday</br>");
break;
case 5:
document.write("Friday</br>");
break;
case 6:
document.write("Saturday</br>");
default:
document.write("error day</br>");
break;
}
//string to number
num=Number("3.14");
document.write(typeof(num),num,"</br>");
num=Number(" ");
document.write(typeof(num),num,"</br>");//0
num=Number("hello");
document.write(typeof(num),num,"</br>");//NaN
num=+"3.14";
document.write(typeof(num),num,"</br>");//3.14
str="hello";
num=+str;
document.write(typeof(num),num,"</br>");//NaN
//boolean to number
document.write(Number(true),"</br>");
document.write(Number(false),"</br>");
//Date to number
document.write((new Date()).getTime(),"</br>");
document.write(Number(new Date()),"</br>");
//auto transform
document.write(5+null,"</br>");//null to 0
document.write("5"+null,"</br>");//null to "null"
document.write("5"+1,"</br>");//1 to "1"
document.write("5"*2,"</br>");//"5" to 5