为什么javascript的"in"运算符在测试时是否返回true,如果0不存在于不包含0的数组中?

Mar*_*son 43 javascript arrays in-operator

为什么Javascript中的"in"运算符在测试时是否返回true,如果数组中存在"0",即使数组似乎不包含"0"?

例如,这返回true,并且有意义:

var x = [1,2];
1 in x; // true
Run Code Online (Sandbox Code Playgroud)

这返回false,并且有意义:

var x = [1,2];
3 in x; // false
Run Code Online (Sandbox Code Playgroud)

但是这会返回true,我不明白为什么:

var x = [1,2];
0 in x;
Run Code Online (Sandbox Code Playgroud)

Mat*_*hen 76

它指的是索引或键,而不是值. 0并且1是该数组的有效索引.还有有效的钥匙,包括"length""toSource".试试2 in x.那将是错误的(因为JavaScript数组是0索引的).

请参阅MDN文档.


Dea*_*ing 17

in运营商不这样做,你在想它做什么.该in运算符返回true如果指定的操作数是对象的属性.对于数组,true如果操作数是有效索引则返回(如果将数组视为特殊情况对象,其中属性简单地命名为0,1,2,...则有意义)

例如,试试这个:

javascript:var x=[1,4,6]; alert(2 in x);
Run Code Online (Sandbox Code Playgroud)

它也会返回true,因为"2"是数组的有效索引.同样,"0"是数组的索引,因此也返回true.


Sea*_*ean 8

Javascript的in运算符不检查数组中是否包含值.它检查对象是否具有属性或索引.所以var x = [4,5]; 4 in x; //false 1 in x; //true.

因为长度是x的属性, "length" in x; //true


ken*_*bec 6

现代浏览器(IE除外)支持一些可以在数组中查找值的方法.

的indexOf和lastIndexOf返回其自变量的精确匹配的第一(或最后)索引阵列,或-1,如果没有匹配元件被发现.

if(A.indexOf(0)!= -1){
    // the array contains an element with the value 0.
}
Run Code Online (Sandbox Code Playgroud)

您可以向IE和旧浏览器添加一种或两种方法 -

if(![].indexOf){
    Array.prototype.indexOf= function(what, i){
        i= i || 0;
        var L= this.length;
        while(i< L){
            if(this[i]=== what) return i;
            ++i;
        }
        return -1;
    }
    Array.prototype.lastIndexOf= function(what, i){
        var L= this.length;
        i= i || L-1;
        if(isNaN(i) || i>= L) i= L-1;
        else if(i< 0) i += L;
        while(i> -1){
            if(this[i]=== what) return i;
            --i;
        }
        return -1;
    }
}
Run Code Online (Sandbox Code Playgroud)


Bra*_*ang 6

我猜你之前用过 Python,在 JS 中,使用 Array.prototype.includes

let x = [1, 2]
x.includes(1) // true
Run Code Online (Sandbox Code Playgroud)

运算符中检查数组的索引而不是值

0 in [1, 2] // true
2 in [1, 2] // false
Run Code Online (Sandbox Code Playgroud)