首页 > typeof返回结果整理

typeof返回结果整理

var p = new Array();
typeof p;
p是一个数组(或者说是数组对象是不是更合理一点),此时p返回的是"object"

typeof Array;
返回的是"function"

写出来整理一下发现因为使用了构造函数,所以p肯定是个对象,但是Array只是个函数(如果理解的不正确,欢迎指正)

typeof的返回值有undefined boolean string number object function
找了一些比较容易搞错的例子:
typeof NaN //返回number
typeof Math //返回object
typeof Global //"undefined" Global对象不属于其他对象的属性方法,级别比typepf高
typeof window //"object"
typeof String //"function"
typeof Boolean //"function"
typeof Number //"function"

还有其他容易搞错的吗?希望提供一下~~


typeof 1 //'number'
typeof new Number(1) //'object'
typeof 'str' //'string'
typeof new String('str') //'object'

鉴于typeof如此的不靠谱,借用Object.prototype.toString是更稳妥的做法:

Object.prototype.toString.call(1); // '[object Number]'
Object.prototype.toString.call(new Number); //'[object Number]'
Object.prototype.toString.call([]); // '[object Array]'

封装一个靠谱的类型检测函数:

function classOf(obj) {
    return Object.prototype.toString.call(obj).slice(8, -1);
}
classOf([]); //'Array'

typeof null = 'object';
typeof undefined = 'undefined';
【热门文章】
【热门文章】