js的内置类型
- 空值(null)
- 未定义(undefined)
- 布尔值(boolean)
- 数字(number)
- 字符串(string)
- 对象(object)
- 符号(symbol,es6中新增)
我们通常用typeof来判断一个变量的类型
typeof undefined === 'undefined'; //true
typeof true === 'boolean'; //true
typeof 42 === 'number'; //true
typeof '42' === 'string'; //true
typeof {life:42} === 'object'; //true
typeof Symbol() === 'symbol' //true
特殊情况(1)
typeof null === 'object'; //true
所以我们在判断null类型时,要用:
var a = null;
(!a && typeof a === 'object'); //true
特殊情况(2)
typeof function a(){...} === 'function'; //true
function实际上是object的一个子类型;具体来说,函数是可调用对象,它有一个内部属性[[Call]],该属性使其可以被调用;
函数不仅仅是对象,还可以拥有属性:
function a(b,c){}
console.log(a.length) //2, 因为该函数声明了两个命名参数
特殊情况(3)
typeof [1,2,3] === 'object'; //true;
数组也是object的一个子类型
后续会继续更新几篇有关类型的文章,感觉有用的兄弟们,可以关注一下撒!!!