我怎么能只保留符合特定条件的数组的项目? [英] How can I only keep items of an array that match a certain condition?

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

问题描述

我有一个数组,我想对其进行过滤,只包含符合特定条件的项目。这可以在JavaScript中做了什么?

一些例子:

  [1,2,3,4,5,6,7,8] //我只想要[2,4,6,8],即,偶数[这,是,一个,阵,同,几个,串,制造,向上,A,句。] //我只要的话,2个或更少的字母:[是,一个,上,一个][真,假,4,0,ABC,,0] //只保留truthy值:真,4,ABC,0]


解决方案

有关这一点,你可以使用的 阵列#过滤器() 方法,ECMAScript5介绍。它在所有浏览器的支持,除了IE8和更低的,和Firefox的古老的版本。如果出于某种原因,你需要支持这些浏览器,你可以使用<一个href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter#Polyfill\"相对=nofollow>的方法填充工具。

过滤器()带一个函数作为第一个参数。对于数组的每一项,你的函数传递三个参数 - 当前项目的价值,其在数组中的索引,而该数组本身。如果你的函数返回真正(或truthy值,例如 1 比萨 42 ),该项目将包括在结果中。否则,它不会。 过滤器()返回新的的阵列 - 你原来的阵列将保持不变。这意味着,你需要保存在某个地方的价值,或者它会丢失。

现在,在从问题的例子:

(我使用脚本来添加一个可视化的控制台来饶你打开它自己的麻烦。来支持我的功能要求的添加一个控制台栈片断。)

\r
\r

VAR myNumbersArray = [1,2,3,4,5,6,7 ,8];\r
的console.log(myNumbersArray.filter(功能(NUM){\r
  返回(NUM%2)!; //保持整除的数字由2\r
}));\r
的console.log(myNumbersArray); //看到的 - 它并没有改变!\r
\r
VAR myStringArray = [这,是,一个,阵,同,几个,串,制造,向上,A,句。];\r
的console.log(myStringArray.filter(功能(STR){\r
  返回str.length&LT; 3; //跟上长度字符串LT; 3\r
}));\r
的console.log(myStringArray);\r
\r
VAR myBoolArray = [真,假,4,0,ABC,,0];\r
的console.log(myBoolArray.filter(布尔));\r
//哇,看看那招!\r
的console.log(myBoolArray);

\r

&LT;! - 结果窗格中控制台输出;见http://meta.stackexchange.com/a/242491 - &GT;\r
&LT;脚本src=\"http://gh-canon.github.io/stack-snippet-console/console.min.js\"></script>\r
\r
\r

和完整性,也使用索引和阵列参数为例:从阵列中删除重复:

\r
\r

myarray的无功= [1,1,2,3,4,5,6 ,1,2,8,2,5,2,52,48,123,43,52]\r
的console.log(myArray.filter(功能(价值指数,数组){\r
   返回array.indexOf(值)===指数;\r
}));

\r

&LT;! - 结果窗格中控制台输出;见http://meta.stackexchange.com/a/242491 - &GT;\r
&LT;脚本src=\"http://gh-canon.github.io/stack-snippet-console/console.min.js\"></script>\r
\r
\r

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?

Some examples:

[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"]

解决方案

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() 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:

(I'm using a script to add a visual console to spare you the trouble of opening it up yourself. Come support my feature request to add a console to Stack Snippets.)

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);

<!-- results pane console output; see http://meta.stackexchange.com/a/242491 -->
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>

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;
}));

<!-- results pane console output; see http://meta.stackexchange.com/a/242491 -->
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>

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

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