簡體   English   中英

為什么在測試不包含 0 的數組中是否存在 0 時,javascript 的“in”運算符返回 true?

[英]Why does javascript's “in” operator return true when testing if 0 exists in an array that doesn't contain 0?

為什么 Javascript 中的“in”運算符在測試數組中是否存在“0”時返回 true,即使數組似乎不包含“0”?

例如,這返回 true,並且有意義:

var x = [1,2];
1 in x; // true

這將返回 false,並且是有道理的:

var x = [1,2];
3 in x; // false

然而,這返回true,我不明白為什么:

var x = [1,2];
0 in x;

它指的是索引或鍵,而不是值。 01是該數組的有效索引。 還有一些有效的鍵,包括"length""toString" 2 in x嘗試2 in x 那將是錯誤的(因為 JavaScript 數組是 0 索引的)。

請參閱MDN 文檔

in運算符不會做您認為它會做的事情。 如果指定的操作數是對象的屬性,則in運算符返回true 對於數組,如果操作數是有效索引,則返回true (如果將數組視為特殊情況對象,其中屬性僅命名為 0、1、2...,則這是有意義的)

例如,試試這個:

var x=[1,4,6];
alert(2 in x);

它也會返回true ,因為“2”是數組的有效索引。 同樣,“0”是數組的索引,因此也返回true

Javascript 的in運算符不檢查值是否包含在數組中。 它檢查對象是否具有屬性或索引。 所以var x = [4,5]; 4 in x; //false 1 in x; //true var x = [4,5]; 4 in x; //false 1 in x; //true var x = [4,5]; 4 in x; //false 1 in x; //true

因為長度是 x 的屬性,所以 x 中的"length" in x; //true "length" in x; //true

現代瀏覽器(IE 除外)支持幾種可以在數組中查找值的方法。

indexOf 和 lastIndexOf 返回數組中其參數完全匹配的第一個(或最后一個)索引,如果未找到匹配元素,則返回 -1。

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

您可以向 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;
    }
}

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

let x = [1, 2]
x.includes(1) // true

運算符中檢查數組的索引而不是值

0 in [1, 2] // true
2 in [1, 2] // false

就像 js for in循環迭代對象屬性一樣, in運算符檢查指定的屬性是否在指定的對象或其原型鏈中。 它不檢查元素是否在數組中。

假設 x 是一個數組,使用x.includes(element)在 nodejs/modern-browsers 中返回true/false 至於loop ,使用for(let element of x)因為 x 是一個 js iterable

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM