typeof

2019-06-17  本文已影响0人  子心_

typeof可用来检测数据类型:

typeof 123 //number
typeof '123' //string
typeof true // boolean
typeof false //boolean
typeof undefined // undefined
typeof Math.abs // function
typeof function () {} // function

需要注意的是typeof无法区分null、Array和通常意义上的object:

typeof null // object
typeof [] // object
typeof {} // object

有趣的是,当数据使用了new关键字和包装对象以后,数据都会变成Object类型,而不使用new关键字时,Number()、Boolean和String()被当做普通函数,把任何类型的数据转换为number、boolean和string类型:

typeof new Number(123); //'object'
typeof Number(123); // 'number'

typeof new Boolean(true); //'object'
typeof Boolean(true); // 'boolean'

typeof new String(123); // 'object'
typeof String(123); // 'string'

除了null和undefined外,对象都有toString()方法,并且number对象调用toString()报错SyntaxError:

123.toString();  // SyntaxError
123..toString();  // '123', 注意是两个点!
(123).toString();  // '123'

总结:

上一篇 下一篇

猜你喜欢

热点阅读