如何看待typeof?

typeof判断基本数据类型

这种方法对于一些常用的类型来说那算是毫无压力,比如Function、String、Number、Undefined等,如:

number
typeof(10);
typeof(NaN);
//NaN在JavaScript中代表的是特殊非数字值,它本身是一个数字类型。
typeof(Infinity);
boolean
typeof(true);
typeof(false);
string
typeof("abc");
undefined
typeof(undefined);
typeof(a);//不存在的变量
function
typeof(Array);
typeof(Date);

typeof判断复合类型

对于复合类型(Object,Array,Function)却只能识别Function。typeof可以看作JS内部已经定义好的各个类型返回其对应的字符串,它不深入值本身,不进行类型转换,只针对于当前值返回其对应的类型值。

//对象,数组,null返回object
typeof(null);
typeof(window);
typeof(Array);

使用typeof bar ===“object”来确定bar是否是一个对象的缺憾?

JavaScript中令人惊讶的问题null也被认为是一个对象!
因此,对于大多数开发人员来说,下面的代码会将true(而不是false)打印到控制台

var bar = null;
console.log(typeof bar === "object")//true

只要知道这一点,就可以通过检查bar是否为空来轻松避免该问题:

console.log((bar !== null) && (typeof bar === "object")); // logs false

为了让我们的答案更加的完整,还有两件事值得注意: 首先,如果bar是一个函数,上面的解决方案将返回false。在大多数情况下,这是所期望的行为,但是在您希望函数返回true的情况下,您可以将上述解决方案修改为:

console.log((bar !== null) && ((typeof bar === "object") || (typeof bar === "function")));

其次,如果bar是数组,则上述解决方案将返回true(例如,如果var bar = [];)。在大多数情况下,这是所希望的行为,因为数组确实是对象,但是在您想要对数组也是false的情况下,可以将上述解决方案修改为:

console.log((bar !== null) && (typeof bar === "object") && (toString.call(bar) !== "[object Array]"));

但是,还有一个替代方法对空值,数组和函数返回false,但对于对象则为true:

console.log((bar !== null) && (bar.constructor === Object));

猜你喜欢

转载自blog.csdn.net/bangbanggangan/article/details/81279999