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

2022-01-31 00:00:00 arrays javascript in-operator

为什么 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;

推荐答案

指的是索引或键,而不是值.01 是该数组的有效索引.还有有效的键,包括 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 文档.

相关文章