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

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


例如,这返回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;


www说
浏览 904回答 3
3回答

Helenr

它引用索引或键,而不是值。 0并且1是该阵列的有效指标。还有一些有效的键,包括"length"和"toSource"。尝试2 in x。这将是错误的(因为JavaScript数组的索引为0)。

largeQ

该in运营商不这样做,你在想它做什么。该in运营商的回报true,如果指定的操作数是对象的属性。对于数组,它返回true操作数是否为有效索引(将数组视为特殊情况下的对象,在该对象中将属性简单地命名为0、1、2,...是有意义的)例如,尝试以下操作:javascript:var x=[1,4,6]; alert(2 in x);它还将返回true,因为“ 2”是数组的有效索引。同样,“ 0”是数组的索引,因此也返回true。

慕码人2483693

除IE外,现代浏览器都支持几种可以在数组中查找值的方法。indexOf和lastIndexOf返回其参数在数组中完全匹配的第一个(或最后一个)索引;如果找不到匹配的元素,则返回-1。if(A.indexOf(0)!= -1){&nbsp; &nbsp; // the array contains an element with the value 0.}您可以在IE和旧版浏览器中添加一种或两种方法,if(![].indexOf){&nbsp; &nbsp; Array.prototype.indexOf= function(what, i){&nbsp; &nbsp; &nbsp; &nbsp; i= i || 0;&nbsp; &nbsp; &nbsp; &nbsp; var L= this.length;&nbsp; &nbsp; &nbsp; &nbsp; while(i< L){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(this[i]=== what) return i;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ++i;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return -1;&nbsp; &nbsp; }&nbsp; &nbsp; Array.prototype.lastIndexOf= function(what, i){&nbsp; &nbsp; &nbsp; &nbsp; var L= this.length;&nbsp; &nbsp; &nbsp; &nbsp; i= i || L-1;&nbsp; &nbsp; &nbsp; &nbsp; if(isNaN(i) || i>= L) i= L-1;&nbsp; &nbsp; &nbsp; &nbsp; else if(i< 0) i += L;&nbsp; &nbsp; &nbsp; &nbsp; while(i> -1){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(this[i]=== what) return i;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; --i;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return -1;&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP