为什么([a],"b"]中的"a")产生假,而([1,2]中的1)产生真? [英] Why does ("a" in ["a","b"]) yield false, and (1 in [1,2]) yield true?

查看:72
本文介绍了为什么([a],"b"]中的"a")产生假,而([1,2]中的1)产生真?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
运算符中的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 ?

推荐答案

- 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)产生真?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆