Why does (“a” in [“a”,“b”]) yield false, and (1 in [1,2]) yield true? [duplicate]

前提是你 提交于 2020-02-06 03:58:19

问题


Possible Duplicate:
javascript in operator

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 ?


回答1:


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.

You usually would use it on plain objects, not on arrays. Like "a" in {a:1} === true, or "b" in {a:1} === false.



来源:https://stackoverflow.com/questions/11808263/why-does-a-in-a-b-yield-false-and-1-in-1-2-yield-true

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!