此代码目前正在完成我要求的工作,但我想知道是否有更好的方法,因为调用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!");
}
}
}
答案 0 :(得分:4)
您可以将includes
方法与filter
方法结合使用,该方法将provided
回调方法应用于数组中的每个项目。
var names = ["Jensen", "Cody", "Darren", "Styles", "Rhyjen"];
console.log(names.filter(a=>a.toLowerCase().includes("j")));
&#13;
答案 1 :(得分:2)
只需使用indexOf('j')
。使用带有Array#forEach
的数组进行迭代,然后将每个文本转换为lowercase
。然后匹配j
的索引
var names = ["Jensen", "Cody", "Darren", "Styles", "Rhyjen"];
names.forEach(a => a.toLowerCase().indexOf('j') > -1? console.log('Name with the letter J detected!'):'')
&#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