内置类型
JavaScript有七种内置类型(包含ES6的symbol):
- null
- undefined
- string
- number
- boolean
- object
- symbol
检测类型
我们可以用typeof运算符来查看值的类型,它始终返回值类型的字符串值。有意思的是这七种类型和它们的字符串值并不一一对应:
typeof undefined === 'undefined'; // true
typeof '' === 'string'; // true
typeof 1 === 'number'; // true
typeof true === 'boolean'; // true
typeof {} === 'object'; // true
typeof Symbol() === 'symbol'; // true
以上六种类型均与其字符串值相同,只有null类型不在此列,null的字符串值是object。
typeof null === 'object'; // true
还有一种情况,function函数是属于object的一个子类型,但是其字符串值确实function。
typeof function () {} === 'function'; // true
undefined 和 undeclared
变量在声明后并没有初始化值时,默认值为undefined。
var a;
typeof a; // 'undefined'
没有在作用域中声明过的变量,是undeclared,但是typeof一个未声明的值却是'undefined',这也是typeof的一个安全机制
var a;
a; // undefined
b; // b is not defined
typeof a; // 'undefined'
typeof b; // 'undefined'
小结
JavaScript有七种内置类型:
null、undefined、boolean、string、number、object、symbol。
通过typeof检测null和function,返回的分别是object和function。
已声明未赋值(undefined)和未声明未赋值(undeclared)