javascript 类型转换语法

1、转字符串类型:String(v)或v.toString()

2、转数字:Number(v)

3、自动转换:连接符+的一方是字符串,则另一方也会被转成字符串;其它算术运算符会把另一方转成数字。

//number to string
var str=String(123);
var str2=String(100*2);
document.write(str,"
",str2,"
"); num=3.141592627; str=num.toString(); document.write(str,"
"); str=num.toFixed(2);//3.14 document.write(str,"
"); str=num.toPrecision(4);//3.142 document.write(str,"
"); num/=100; str=num.toExponential(3);//3.142e-2 document.write(str,"
"); //boolean to string str=String(true); document.write(str==="true","
"); str=false.toString(); document.write(str==="false","
"); //Date to string str=String(Date()); document.write(str,"
"); str=Date().toString(); document.write(str,"
"); //get year var date=new Date(); document.write(date.getFullYear(),"year
"); //get month document.write(date.getMonth()+1,"month
"); //get date document.write(date.getDate(),"date
"); //get hour document.write(date.getHours(),"hour
"); //get minute document.write(date.getMinutes(),"minute
"); //get second document.write(date.getSeconds(),"second
"); //get millisecond document.write(date.getMilliseconds(),"millisecond
"); //get all milliseconds document.write(date.getTime(),"time
"); //get day in week var day=date.getDay(); switch(day){ case 0: document.write("sunday
"); break; case 1: document.write("monday
"); break; case 2: document.write("Tuesday
"); break; case 3: document.write("Wednsday
"); break; case 4: document.write("Thursday
"); break; case 5: document.write("Friday
"); break; case 6: document.write("Saturday
"); default: document.write("error day
"); break; } //string to number num=Number("3.14"); document.write(typeof(num),num,"
"); num=Number(" "); document.write(typeof(num),num,"
");//0 num=Number("hello"); document.write(typeof(num),num,"
");//NaN num=+"3.14"; document.write(typeof(num),num,"
");//3.14 str="hello"; num=+str; document.write(typeof(num),num,"
");//NaN //boolean to number document.write(Number(true),"
"); document.write(Number(false),"
"); //Date to number document.write((new Date()).getTime(),"
"); document.write(Number(new Date()),"
"); //auto transform document.write(5+null,"
");//null to 0 document.write("5"+null,"
");//null to "null" document.write("5"+1,"
");//1 to "1" document.write("5"*2,"
");//"5" to 5

你可能感兴趣的:(javascript 类型转换语法)