如何只保留匹配特定条件的数组项? [英] How can I only keep items of an array that match a certain condition?

查看:26
本文介绍了如何只保留匹配特定条件的数组项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组,我想过滤它以仅包含匹配特定条件的项目.这可以在 JavaScript 中完成吗?

I have an array, and I want to filter it to only include items which match a certain condition. Can this be done in JavaScript?

一些例子:

[1, 2, 3, 4, 5, 6, 7, 8] // I only want [2, 4, 6, 8], i.e. the even numbers

["This", "is", "an", "array", "with", "several", "strings", "making", "up", "a", "sentence."] // I only want words with 2 or fewer letters: ["is", "an", "up", "a"]

[true, false, 4, 0, "abc", "", "0"] // Only keep truthy values: [true, 4, "abc", "0"]

推荐答案

为此,您可以使用 Array#filter() 方法,在 ECMAScript5 中引入.所有浏览器都支持它,除了 IE8 及更低版本,以及旧版本的 Firefox.如果出于某种原因,您需要支持这些浏览器,您可以使用 polyfill 用于该方法.

For this, you can use the Array#filter() method, introduced in ECMAScript5. It is supported in all browsers, except for IE8 and lower, and ancient versions of Firefox. If, for whatever reason, you need to support those browsers, you can use a polyfill for the method.

filter() 接受一个函数作为它的第一个参数.对于数组中的每一项,您的函数都会传递三个参数——当前项的值、它在数组中的索引以及数组本身.如果您的函数返回 true(或一个真值,例如 1"pizza"42),该项目将包含在结果中.否则,它不会.filter() 返回一个 new 数组 - 您的原始数组将保持不变.这意味着您需要将值保存在某处,否则它将丢失.

filter() takes a function as its first argument. For every item of the array, your function is passed three arguments - the value of the current item, its index in the array, and the array itself. If your function returns true (or a truthy value, e.g. 1, "pizza", or 42), that item will be included in the result. Otherwise, it won't. filter() returns a new array - your original array will be left unmodified. That means that you'll need to save the value somewhere, or it'll be lost.

现在,在问题的示例中:

Now, in the examples from the question:

var myNumbersArray = [1, 2, 3, 4, 5, 6, 7, 8];
console.log(myNumbersArray.filter(function(num){
  return !(num % 2); // keep numbers divisible by 2
}));
console.log(myNumbersArray); // see - it hasn't changed!

var myStringArray = ["This", "is", "an", "array", "with", "several", "strings", "making", "up", "a", "sentence."];
console.log(myStringArray.filter(function(str){
  return str.length < 3; // keep strings with length < 3
}));
console.log(myStringArray);

var myBoolArray = [true, false, 4, 0, "abc", "", "0"];
console.log(myBoolArray.filter(Boolean));
// wow, look at that trick!
console.log(myBoolArray);

为了完整性,还有一个使用索引和数组参数的示例:从数组中删除重复项:

And for completeness, an example that also uses the index and array parameters: Removing duplicates from the array:

var myArray = [1,1,2,3,4,5,6,1,2,8,2,5,2,52,48,123,43,52];
console.log(myArray.filter(function(value, index, array) {
   return array.indexOf(value) === index;
}));

这篇关于如何只保留匹配特定条件的数组项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆