简体   繁体   English

如何判断 javascript 变量是否为数组且仅是数组

[英]How to tell whether a javascript variable is an Array and only an Array

what's the best way to determine whether a Javascript variable is an array, but has no other user-defined properties?确定 Javascript 变量是否为数组但没有其他用户定义属性的最佳方法是什么? 'instanceof Array' doesn't do this. 'instanceof Array' 不这样做。

eg例如

var var1 = [10,11];
var1['key1'] = 'extraProperty';

var1 instanceof Array;    //returns true
var isOnlyArray = function(o) {
    if (! (Object.prototype.toString.call(o) === "[object Array]")) {
        return false;
    }
    for (property in o) { 
        if (o.hasOwnProperty(property)) {
            var asInt = parseInt(property, 10);
            if (!(0 <= asInt && asInt < o.length)
                || String(asInt) !== property) {
                return false;
            }
        }
    }

    return true;
}

This function confirms that it's an Array and that every defined property on an object is an integer index that's in the range specified by .length .这个 function 确认它是一个Array ,并且 object 上的每个定义的属性都是一个 integer 索引,它在.length指定的范围内。

var a = [1, 2];
console.log(isOnlyArray(a)); // true
a[2] = 4;
console.log(isOnlyArray(a)); // true
a["foo"] = 5;
console.log(isOnlyArray(a)); // false

I don't think that you can verify the integrity of something that was created as an Array object.我认为您无法验证作为Array object 创建的内容的完整性。 Javascript won't prohibit you from adding properties to such an object. Javascript 不会禁止您向此类 object 添加属性。

You could iterate through the object's properties and return false if you see one that you don't think should be in Array , but that's still no guarantee that even the normal properties haven't had their values mangled.可以遍历对象的属性并返回false如果您看到一个您认为不应该在Array中的属性,但这仍然不能保证即使是普通属性的值也没有被破坏。

Just don't add properties to Array s, then you won't have this problem.只是不要向Array添加属性,那么您就不会有这个问题。 That you're asking about this kind of implies that you've done something quite wrong somewhere else in your code.你问这种问题意味着你在代码的其他地方做了一些非常错误的事情。

In general, you can't distinguish array and object.一般来说,你无法区分数组和 object。 Object can be used as an array and vice versa. Object 可以用作数组,反之亦然。 Example:例子:

var fancyObj = {
    favoriteFood: "pizza",
    add: function(a, b){
        return a + b;
    }
};
fancyObj.add(2,3); // returns 5
fancyObj['add'](2,3); // ditto.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM