代碼:如何找到在陣列中的多個元素 - JAVASCRIPT,ES6
let names= ["Style","List","Raw"];
let results= names.find(x=> x.includes("s");
console.log(results); //
如何獲得包含「S」從數組名的名稱, 目前,我只得到一個元素結果但我需要所有事件。
代碼:如何找到在陣列中的多個元素 - JAVASCRIPT,ES6
let names= ["Style","List","Raw"];
let results= names.find(x=> x.includes("s");
console.log(results); //
如何獲得包含「S」從數組名的名稱, 目前,我只得到一個元素結果但我需要所有事件。
你必須要在這種情況下使用filter
,
let names= ["Style","List","Raw"];
let results= names.filter(x => x.includes("s"));
console.log(results); //["List"]
如果你希望它是不區分大小寫然後用下面的代碼,
let names= ["Style","List","Raw"];
let results= names.filter(x => x.toLowerCase().includes("s"));
console.log(results); //["Style", "List"]
爲了使案件敏感,我們有使字符串的字符全部爲小寫。
使用過濾器而不是查找。
let names= ["Style","List","Raw"];
let results= names.filter(x => x.includes("s"));
console.log(results);
但你也可以使用的forEach()方法:
var names = ["Style","List","Raw"];
var results = [];
names.forEach(x => {if (x.includes("s") || x.includes("S")) results.push(x)});
console.log(results); // [ 'Style', 'List' ]
或者,如果您prefere:
names.forEach(x => {if (x.toLowerCase().includes("s")) results.push(x)});
如果使用過濾器你的forEach在做什麼會被過濾器來完成。 Filter返回一個數組,而forEach不會返回任何東西。所以這是更好的可讀性:) – Vatsal