typeof 123; // 'number'typeof NaN; // 'number'typeof 'str'; // 'string'typeof true; // 'boolean'typeof undefined; // 'undefined'typeof Math.abs; // 'function'typeof null; // 'object'typeof []; // 'object'typeof {}; // 'object'

numberstringbooleanfunctionundefined有别于其他类型。

null的类型是objectArray的类型也是object,如果我们用typeof将无法区分。

总结一下,有这么几条规则需要遵守:

  • 不要使用new Number()new Boolean()new String()创建包装对象;

  • parseInt()parseFloat()来转换任意类型到number

  • String()来转换任意类型到string,或者直接调用某个对象的toString()方法;

  • 通常不必把任意类型转换为boolean再判断,因为可以直接写if (myVar) {...}

  • typeof操作符可以判断出numberbooleanstringfunctionundefined

  • 判断Array要使用Array.isArray(arr)

  • 判断null请使用myVar === null

  • 判断某个全局变量是否存在用typeof window.myVar === 'undefined'

  • 函数内部判断某个变量是否存在用typeof myVar === 'undefined'

  • nullundefined没有toString()方法。

  • number对象调用toString()报SyntaxError。

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