美文网首页
JS中判断变量是array还是object

JS中判断变量是array还是object

作者: 嘤嘤嘤998 | 来源:发表于2019-02-14 14:41 被阅读0次
1. typeof操作符

如果你只是用typeof来检查该变量,不论是array还是object,都将返回‘object'。

alert(typeof null); // "object" 
alert(typeof function () { 
    return 1; 
}); // "function" 
alert(typeof '梦龙小站'); // "string" 
alert(typeof 1); // "number" 
alert(typeof a); // "undefined" 
alert(typeof undefined); // "undefined" 
alert(typeof []); // "object" 
2.instanceof操作符
var arr = [1,2,3,1]; 
alert(arr instanceof Array); // true 
3.对象的constructor属性
var arr = [1,2,3,1]; 
alert(arr.constructor === Array); // true 

第2种和第3种方法貌似无懈可击,但是实际上还是有些漏洞的,当你在多个frame中来回穿梭的时候,这两种方法就亚历山大了。由于每个iframe都有一套自己的执行环境,跨frame实例化的对象彼此是不共享原型链的,因此导致上述检测代码失效!

4.Object.prototype.toString
function isArrayFn (o) { 
    return Object.prototype.toString.call(o) === '[object Array]'; 
} 
var arr = [1,2,3,1]; 
alert(isArrayFn(arr));    // true 

为什么不直接o.toString()?嗯,虽然Array继承自Object,也会有 toString方法,但是这个方法有可能会被改写而达不到我们的要求,而Object.prototype则是老虎的屁股,很少有人敢去碰它的,所以能一定程度保证其“纯洁性”

5.Array.isArray()

ECMAScript5将Array.isArray()正式引入JavaScript,目的就是准确地检测一个值是否为数组。IE9+、 Firefox 4+、Safari 5+、Opera 10.5+和Chrome都实现了这个方法。但是在IE8之前的版本是不支持的。

6.判断数组的最佳写法:
var arr = [1,2,3,1]; 
var arr2 = [{ abac : 1, abc : 2 }]; 
function isArrayFn(value){ 
    if (typeof Array.isArray === "function") { 
        return Array.isArray(value); 
    }else{ 
        return Object.prototype.toString.call(value) === "[object Array]"; 
    } 
} 
alert(isArrayFn(arr));     // true 
alert(isArrayFn(arr2));    // true 

相关文章

网友评论

      本文标题:JS中判断变量是array还是object

      本文链接:https://www.haomeiwen.com/subject/szjeeqtx.html