首页 > Web开发 > 详细

JS typeof 与 instanceof

时间:2015-11-13 14:49:52      阅读:295      评论:0      收藏:0      [点我收藏+]

JS中常用来判定变量类型的两个函数为 typeof 和 instanceof

typeof variables的结果有 number, boolean, string, function, object[null, Array, Obeject, String,Date.....], undefined

要注意的地方是 typeof null的结果为object

null和undefined并不是等价的

var tmp = null; // 虽然tmp是null,但我也定义了
var undef; //声明但没定义
alert(typeof tmp); // object
alert(typeof undef); // undefined

所以判断一个值是不是null的时候直接用 tmp == null即可,切勿使用typeof,null是一种特殊的对象

// 标量 //
typeof 123; // number
typeof ‘string‘; // string
typeof true; // boolean
// 函数 //
typeof function(){}; //function
// 对象 //
typeof new String(‘string‘); // object
typeof null; //object

instanceof 可以判断非标量的类型

‘string‘ instanceof String; // false
new String(‘string‘) instanceof String; // true


JS typeof 与 instanceof

原文:http://my.oschina.net/sallency/blog/529901

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!