typeof

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'

总结:

  • typeof操作符可以判断出number、boolean、string、function和undefined;
  • 可以用String()或调用某个对象的toString()方法来转换任意类型到string;
  • 用parseInt()或parseFloat()来转换任意类型到number;
  • 判断Array要使用Array.isArray(arr);
  • 判断null请使用 thisVar === null;
  • 判断某个全局变量是否存在用typeof window.myVar === 'undefined';
  • 函数内部判断某个变量是否存在用typeof myVar === 'undefined';
  • 通常不必把任意类型转换为boolean再判断,因为可以直接写if (myVar) { ... };
  • 不要使用new Number()、new Boolean()、new String()创建包装对象;
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容