gpt4 book ai didi

javascript - 检查 javascript 数组中的字符串元素

转载 作者:行者123 更新时间:2023-11-30 07:27:25 25 4
gpt4 key购买 nike

这是怎么回事?

var colours = ['red','green', 'blue']
console.log('blue' in colours); // outputs false

输出false,我还以为应该是trye呢

谢谢

最佳答案

由于您正在处理一个 Array ,所以您不能那样检查它。 Arrays 为您提供了 Array.prototype.indexOf 方法来确定其中是否有内容:

console.log( colours.indexOf( 'blue' ) > -1 );

解释:

ECMAscript 中的数组只是专门的对象。这意味着你的 Array 真的很像

colours = {
0: 'red',
1: 'green',
2: 'blue'
};

因为 in 操作符只检查对象 keys,你不能用它检查值。例如,您确实可以检查 if('1' in colours)(这将返回 true),但这没有多大意义。同样,对数组使用 .indexOf()

旁注:ECMAscript Harmony(ES.Next 或 ES6)将提供 for of 循环,它枚举对象值而不是键。我不太确定我们是否可以像使用 in 一样使用 of 运算符,但它会非常有用。

关于javascript - 检查 javascript 数组中的字符串元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9812711/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com