如何在数组中找到多个元素-Javascript,ES6
代码: 如何从数组名称中获取包含“s”的名称, 目前,我得到的结果只有一个元素,但我需要所有出现的元素。您必须在此上下文中使用如何在数组中找到多个元素-Javascript,ES6,javascript,ecmascript-6,Javascript,Ecmascript 6,代码: 如何从数组名称中获取包含“s”的名称, 目前,我得到的结果只有一个元素,但我需要所有出现的元素。您必须在此上下文中使用 let names= ["Style","List","Raw"]; let results= names.find(x=> x.includes("s"); console.log(results); // 如果希望它不区分大小写,请使用以下代码 let names= ["Style","List","Raw"]; let results= names.fi
let names= ["Style","List","Raw"];
let results= names.find(x=> x.includes("s");
console.log(results); //
如果希望它不区分大小写,请使用以下代码
let names= ["Style","List","Raw"];
let results= names.filter(x => x.includes("s"));
console.log(results); //["List"]
要使其区分大小写,我们必须将字符串的字符全部改为小写。使用filter而不是find
let names= ["Style","List","Raw"];
let results= names.filter(x => x.toLowerCase().includes("s"));
console.log(results); //["Style", "List"]
但也可以使用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' ]
如果使用过滤器,则在forEach中执行的操作将由过滤器完成。筛选器返回数组,而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' ]
names.forEach(x => {if (x.toLowerCase().includes("s")) results.push(x)});