今天看了一篇关于类型转换的文章,总结了一下其中的几种情况。
Biu~~现在开始起飞~~~
1.变量转换
var myVar = "3.14159",
str = ""+ myVar,// to string
int = ~~myVar, // to integer
float = 1*myVar, // to float
bool = !!myVar, /* to boolean - any string with length and any number except 0 are true */
array = [myVar]; // to array
注:转换日期(new Date(myVar))和正则表达式(new RegExp(myVar))必须使用构造函数,创建正则表达式的时候要使用/pattern/flags这样的简化形式。
2.取整同时转换成数值型
//字符型变量参与运算时,JS会自动将其转换为数值型(如果无法转化,变为NaN)'10.567890' | 0//结果: 10//JS里面的所有数值型都是双精度浮点数,因此,JS在进行位运算时,会首先将这些数字运算数转换为整数,然后再执行运算//| 是二进制或, x|0 永远等于x;^为异或,同0异1,所以 x^0 还是永远等于x;至于~是按位取反,搞了两次以后值当然是一样的'10.567890' ^ 0 //结果: 10- 2.23456789 | 0//结果: -2~~-2.23456789//结果: -2
3.日期转数值
//JS本身时间的内部表示形式就是Unix时间戳,以毫秒为单位记录着当前距离1970年1月1日0点的时间单位var d = +new Date(); //1295698416792
4.类数组对象转数组
var arr =[].slice.call(arguments)
下面的实例用的更绝
function test() {var res = ['item1', 'item2']res = res.concat(Array.prototype.slice.call(arguments)) //方法1Array.prototype.push.apply(res, arguments) //方法2
}
5.进制之间的转换
(int).toString(16); // converts int to hex, eg 12 => "C"
(int).toString(8); // converts int to octal, eg. 12 => "14"
parseInt(string,16) // converts hex to int, eg. "FF" => 255
parseInt(string,8) // converts octal to int, eg. "20" => 16
好啦,以上就是这些特殊情况。
Biu~~~