2016-07-27 51 views

回答

15

你必須要在這種情況下使用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"] 

爲了使案件敏感,我們有使字符串的字符全部爲小寫。

1

使用過濾器而不是查找。

let names= ["Style","List","Raw"]; 
let results= names.filter(x => x.includes("s")); 
console.log(results); 
0

但你也可以使用的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)}); 
+0

如果使用過濾器你的forEach在做什麼會被過濾器來完成。 Filter返回一個數組,而forEach不會返回任何東西。所以這是更好的可讀性:) – Vatsal