如何在数组中查找多个元素 - Javascript,ES6

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38618088/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 21:39:52  来源:igfitidea点击:

How to find multiple elements in Array - Javascript ,ES6

javascriptecmascript-6

提问by Gowtham S

Code:

代码:

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

How to get the names which contain "s" from the array names, currently, I am getting only one element as a result but i need all occurrences.

如何从数组名称中获取包含“s”的名称,目前,我只得到一个元素,但我需要所有出现的元素。

回答by Rajaprabhu Aravindasamy

You have to use filterat this context,

你必须filter在这种情况下使用,

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

If you want it to be case insensitive then use the below code,

如果您希望它不区分大小写,请使用以下代码,

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

To make it case in sensitive, we have to make the string's character all to lower case.

为了区分大小写,我们必须将字符串的字符全部设为小写。

回答by ingleback

Use filter instead of find.

使用过滤器代替查找。

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

回答by kevin ternet

But you can also use forEach() method :

但您也可以使用 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' ]

Or if you prefere :

或者,如果您更喜欢:

names.forEach(x => {if (x.toLowerCase().includes("s")) results.push(x)});