问题描述
为什么 Javascript 中的in"运算符在测试数组中是否存在0"时返回 true,即使数组似乎不包含0"?
Why does the "in" operator in Javascript return true when testing if "0" exists in array, even when the array doesn't appear to contain "0"?
例如,这返回 true,并且有意义:
For example, this returns true, and makes sense:
var x = [1,2];
1 in x; // true
这返回false,并且是有道理的:
This returns false, and makes sense:
var x = [1,2];
3 in x; // false
然而这返回true,我不明白为什么:
However this returns true, and I don't understand why:
var x = [1,2];
0 in x;
推荐答案
它指的是索引或键,而不是值.0
和 1
是该数组的有效索引.还有一些有效的键,包括length"
和toString"
.尝试 2 in x
.那将是错误的(因为 JavaScript 数组是 0 索引的).
It refers to the index or key, not the value. 0
and 1
are the valid indices for that array. There are also valid keys, including "length"
and "toString"
. Try 2 in x
. That will be false (since JavaScript arrays are 0-indexed).
请参阅 MDN 文档.
这篇关于为什么 javascript 的“in"运算符在测试不包含 0 的数组中是否存在 0 时返回 true?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!