可能重复: 运算符中的javascript
为什么([[a],"b"]中的"a")产生 false 和([1,2]中的1)产生 true 吗?为什么"a" 与该数组的第一个元素不匹配,而1与它匹配呢?为什么它不能与字符串一起使用?
Why does ("a" in ["a","b"]) yield false, and (1 in [1,2]) yield true ? Is there a reason why "a" does not match the first element of that array and 1 does ? Why won't it work with strings ?
推荐答案in 运算符中的操作是通过键而不是值来检查属性是否存在.长度为2的数组具有一个索引"1" - arr ["1"] 是值 2 .例如,在["a","b"] 中的 0也是 true .该行为与所使用的字符串或数字无关.
The in operator checks for the existence of properties by key, not by value. And your array of length 2 has an index "1" - arr["1"] is the value 2. For example, also 0 in ["a", "b"] is true. The behaviour does not depend on a string or a number being used.
通常将其用于普通对象,而不是数组.类似于{a:1} === true 中的"a"或{a:1} === false 中的"b".
You usually would use it on plain objects, not on arrays. Like "a" in {a:1} === true, or "b" in {a:1} === false.
更多推荐
为什么([a],"b"]中的"a")产生假,而([1,2]中的1)产生真?
发布评论