循环遍历数组索引以搜索某个字母的最佳方法是什么?

时间:2017-05-02 13:46:33

标签: javascript

此代码目前正在完成我要求的工作,但我想知道是否有更好的方法,因为调用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!");
        }
    }
}

5 个答案:

答案 0 :(得分:4)

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

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

答案 1 :(得分:2)

只需使用indexOf('j')。使用带有Array#forEach的数组进行迭代,然后将每个文本转换为lowercase。然后匹配j的索引

&#13;
&#13;
var names = ["Jensen", "Cody", "Darren", "Styles", "Rhyjen"];
names.forEach(a => a.toLowerCase().indexOf('j') > -1? console.log('Name with the letter J detected!'):'')
&#13;
&#13;
&#13;

答案 2 :(得分:1)

如果你...

  • ...想要检测到至少出现一个给定条件,请使用Array.prototype.some
  • ...想要获得给定条件的第一次出现,请使用Array.prototype.find
  • ...想要获得给定条件的所有出现,请使用Array.prototype.filter

var names = ["Jensen", "Cody", "Darren", "Styles", "Rhyjen"];

var someHasJ = names.some(n => n.toLowerCase().includes("j"));
var hasJ = names.find(n => n.toLowerCase().includes("j"));
var allWithJ = names.filter(n => n.toLowerCase().includes("j"));

if (someHasJ) {
  console.log("Name with the letter J detected!");
}

if (hasJ) {
  console.log(hasJ);
}


if (allWithJ.length > 0) {
  console.log(allWithJ);
}

答案 3 :(得分:0)

您可以使用Array#join加入所有项目,然后查看Array#indexOf

var names = ["Jensen", "Cody", "Darren", "Styles", "Rhyjen"];

if (names.join().toLowerCase().indexOf('j') !== -1) {
    console.log('found!');
} else {
    console.log('not found!');
}

答案 4 :(得分:0)

使用some()和indexOf():

使用这样的东西
var names = ["Jensen", "Cody", "Darren", "Styles", "Rhyjen"];

function hasThis(arr, str){
  return arr.some(function(x) {
    return x.toLowerCase().indexOf(str.toLowerCase()) > -1;
  });
}

hasThis(names, 'J'); //return true
hasThis(names, 'Xhj'); //return false
相关问题