gpt4 book ai didi

JavaScript 查找数组中的字符串是否可以在对象中找到

转载 作者:行者123 更新时间:2023-11-28 18:22:39 24 4
gpt4 key购买 nike

我有一个包含不同 Angular 色的对象,还有一个包含特定颜色的数组。

我想做的是查看 Roles.name 是否包含颜色数组中的任何字符串。我尝试过不同的方法,例如:

var colors = ["blue", "yellow", "brown", "red", "green", "pink", "purple"];
var roles = [{"name": "asd"},
{"name": "blue"},
{"name": "yellow"},
{"name": "brown"},
{"name": "red"},
{"name": "green"},
{"name": "pink"},
{"name": "purple"},
{"name": "fgh"},
{"name": "jkl"}];
for (var i = 0; i < roles.length; i++) {
if (roles[i].name.indexOf(colors)) {
console.log(roles[i].name);
}
}

还有

var colors = ["blue", "yellow", "brown", "red", "green", "pink", "purple"];
var roles = [{"name": "asd"},
{"name": "blue"},
{"name": "yellow"},
{"name": "brown"},
{"name": "red"},
{"name": "green"},
{"name": "pink"},
{"name": "purple"},
{"name": "fgh"},
{"name": "jkl"}];
roles.forEach(role => {
if (role.name.indexOf(colors)) {
console.log(role.name);
}
});

但是使用这两个代码,结果是完整的 Angular 色列表。

预期结果是记录到控制台的所有颜色。我得到的是记录到控制台的所有 Angular 色。

最佳答案

您正在向后使用indexOf。它应该是array.indexOf(valueToSearchFor),但你有valueToSearchFor.indexOf(array)。另外,indexOf 返回索引,而不是 bool 值;要测试是否找到该元素,您必须将其与 -1 进行比较。

var colors = ["blue", "yellow", "brown", "red", "green", "pink", "purple"];
var roles = [{"name": "asd"},
{"name": "blue"},
{"name": "yellow"},
{"name": "brown"},
{"name": "red"},
{"name": "green"},
{"name": "pink"},
{"name": "purple"},
{"name": "fgh"},
{"name": "jkl"}];
for (var i = 0; i < roles.length; i++) {
if (colors.indexOf(roles[i].name) != -1) {
console.log(roles[i].name);
}
}

关于JavaScript 查找数组中的字符串是否可以在对象中找到,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39671070/

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