gpt4 book ai didi

javascript - 遍历数组索引以搜索特定字母的最佳方法是什么?

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

这段代码目前可以完成我要求的工作,但我想知道是否有更好的方法,因为调用 names[i][j] 似乎不切实际。

var names = ["Jensen", "Cody", "Darren", "Styles", "Rhyjen"];
for(var i = 0; i < names.length; i++) {
for(var j = 0; j < names[i].length; j++) {
if(names[i][j] === "J" || names[i][j] === "j") {
console.log("Name with the letter J detected!");
}
}
}

最佳答案

您可以将includes 方法与filter 方法结合使用,后者将提供的 回调方法应用于数组中的每个项目。

var names = ["Jensen", "Cody", "Darren", "Styles", "Rhyjen"];
console.log(names.filter(a=>a.toLowerCase().includes("j")));

关于javascript - 遍历数组索引以搜索特定字母的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43739569/

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