JavaScript filter() 方法混淆

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25585353/
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-10-28 04:41:55  来源:igfitidea点击:

JavaScript filter() method confusion

javascript

提问by benvenker

I'm working through JavaScript: The Definitive Guideas part of Learn JavaScript Properly, and I'm having trouble reasoning about the filter()method in Chapter 7's section on Array Methods.

我正在学习JavaScript: The Definitive Guide作为Learn JavaScript Properly 的一部分,我filter()在第 7 章关于数组方法的部分中无法推理该方法。

Here's the example provided:

这是提供的示例:

The filter()method returns an array containing a subset of the elements of the array on which it is invoked. The function you pass to it should be predicate: a function that returns true or false. The predicate is invoked just as for forEach()and map(). If the return value is true, or a value that converts to true, then the element passed to the predicate is a member of the subset and is added to the array that will become the return value.

Examples:

filter()方法返回一个数组,其中包含调用它的数组元素的子集。你传递给它的函数应该是谓词:一个返回真或假的函数。谓词就像 for forEach()and一样被调用map()。如果返回值为真,或转换为真的值,则传递给谓词的元素是子集的成员,并添加到将成为返回值的数组中。

例子:

a = [5, 4, 3, 2, 1];
smallvalues = a.filter(function(x) { return x < 3 });   // [2, 1]
everyother = a.filter(function(x,i) { return i%2==0 }); // [5, 3, 1] 

Where I'm getting confused is how exactly iis applied to xin the the everyotherline. Here's what I thinkis happening:

我感到困惑的地方是如何准确地i应用于xeveryother行。这是我认为正在发生的事情:

  1. i(the index of a[]) is being passed through the function ,x, which applies the predicate to each element of a[]and returns [4, 2].

  2. Then the function says "filter [4, 2]out of a[]"...I'm real fuzzy on how.

  1. i(的索引a[])通过函数 , 传递,该函数x将谓词应用于 的每个元素a[]并返回[4, 2]

  2. 然后函数说“过滤[4, 2]a[]”......我真的很不清楚如何。

When I mess around in the console, I've tried:

当我在控制台中乱搞时,我尝试过:

everyother = a.filter(function(i) { return i%2==0 });  // returns [4, 2]

which is what I would expect, but I don't understand what happens internally in how JS handles the parameters when I change the above code to

这是我所期望的,但我不明白当我将上面的代码更改为

everyother = a.filter(function(x,i) { return i%2==0 }); // returns [5, 3, 1]

(I do know that the array methods are applied like so: function(element, index, array))

(我不知道该阵列方法应用于像这样:function(element, index, array)

For this particular example, it's obvious to me that I could get the expected result another way:

对于这个特定示例,我很明显可以通过另一种方式获得预期结果:

everyother = a.filter(function(x) { return x%2!=0 }); // returns [5, 3, 1]

But I suspect that line of thinking is precisely missing the point the example is trying to get across...I'm just missing it.

但我怀疑这种思路恰恰没有抓住示例试图传达的重点……我只是错过了它。

采纳答案by Wiktor Zychla

When you invoke filterwith a function of two arguments, the first argument binds to the array element value, the second (the optional one) to the element index.

当您filter使用具有两个参数的函数调用时,第一个参数绑定到数组元素值,第二个(可选的)绑定到元素索引。

Your confusion stems from the fact that the input array [5,4,3,2,1]is somewhat specific - elements that have even indexes (5, 3, 1) are odd and elements that have odd indexes (4, 2) are even.

您的困惑源于这样一个事实,即输入数组[5,4,3,2,1]有些特定 - 具有偶数索引 (5, 3, 1) 的元素是奇数,而具有奇数索引 (4, 2) 的元素是偶数。

This makes this filtering predicate ...%2always pick elements of the same 'kind', depending on what you pass as the predicate parameter (value or index) you will get odd or even elements.

这使得此过滤谓词...%2始终选择相同“种类”的元素,这取决于您作为谓词参数(值或索引)传递的内容,您将获得奇数或偶数元素。

My advice to clean up the confusion would be to pick a different array to test your filtering method. The array should mix oddity of indexes and values, something like [1,3,4,5,7,8]. You will immediately observe what happens when the predicate takes a value or an index into account.

我清理混乱的建议是选择一个不同的数组来测试你的过滤方法。该数组应该混合索引和值的奇怪之处,例如[1,3,4,5,7,8]. 您将立即观察当谓词考虑值或索引时会发生什么。

Also remember that when creating a filtering predicate, the namesof formal parameters are arbitrary, what matters is their position. The first parameter, no matter how you call it, stands for the value, the second stands for the index. If you clash your parameter names by accident and you call your first parameter iand then your second parameter ithen it binds to something else in both scenarios.

还要记住,在创建过滤谓词时,形式参数的名称是任意的,重要的是它们的位置。第一个参数,不管怎么称呼,都代表值,第二个代表索引。如果您不小心冲突了参数名称,然后调用了第一个参数i,然后调用了第二个参数,i那么在这两种情况下它都会绑定到其他内容。

回答by Thomas Junk

Your example is really simple and clear:

您的示例非常简单明了:

a = [5, 4, 3, 2, 1];
smallvalues = a.filter(function(x) { return x < 3 });   // [2, 1]
everyother = a.filter(function(x,i) { return i%2==0 }); // [5, 3, 1]

The first one reads: ?return me every element (x), which is lesser than 3?. The result is not astounding.

第一个写着: ? 将小于 3 的每个元素 (x) 返回给我?结果并不令人震惊。

The second one reads: ?return me every element, whose index (i) is even (including 0)?

第二个是:?返回每个元素,其索引 (i) 是偶数(包括 0)

The xis just ignored.

X只是忽略。

You could also have written [5, 4, 3, 2, 1].filter(function(_,x){return x%2===0})

你也可以写 [5, 4, 3, 2, 1].filter(function(_,x){return x%2===0})

See MDNfor Array.prototype.filter().

MDNArray.prototype.filter()

回答by user8182798

a = [5, 4, 3, 2, 1];
everyother = a.filter(function(x,i) { return i%2==0 }); // [5, 3, 1] 

x is each element in the array .(first iteration x = 5, second iteration x=4 , so on..)
i is the index - (first iteration i = 0, second iteration i=1 , so on..)

x 是数组中的每个元素。(第一次迭代 x = 5,第二次迭代 x=4 ,依此类推..)
i 是索引 - (第一次迭代 i = 0,第二次迭代 i=1 ,依此类推..)

So, in the question (for first iteration-i% 2 becomes 0%2 which is equal to 0 and the condition becomes true. And the first element is returned to the array ..hence 5 is returned,). next, 1%2 !=0, so 4 gets removed. 2%2 ==0, hence 3 stays. (so on..)

因此,在问题中(对于第一次迭代-i% 2 变为 0%2 等于 0 并且条件变为真。并且第一个元素返回到数组 ..因此返回 5,)。接下来,1%2 !=0,所以 4 被删除。2%2 ==0,因此停留 3 次。(很快..)

In this syntax :- x is having a value for each iteration, but it isn't used up in the condition.

在此语法中:- x 每次迭代都有一个值,但它没有在条件中用完。

Tip: filter() always expects a boolean value.and whatever gets returned (true or false) determines whether the value(or element) stays in the array or not.

提示:filter() 总是需要一个布尔值。返回的任何值(真或假)决定了值(或元素)是否留在数组中。

回答by Nitesh Ranjan

Its simple... In everyother, iis the index of each element and the only possible values of iare 0,1,2,3,4 as you have five elements in array.

它很简单... In everyother,i是每个元素的索引,唯一可能的值i是 0,1,2,3,4 ,因为数组中有五个元素。

Now out of all values of ionly 0,2,4 are divisible by 2 and that's why you are getting values of those indices i.e [5,3,1].

现在,i只有 0,2,4的所有值都可以被 2 整除,这就是为什么您要获得这些索引的值,即[5,3,1].

回答by Abhilash A S

a = [5, 4, 3, 2, 1];
smallvalues = a.filter(obj => obj < 3); console.log(smallvalues)
everyother = a.filter(ele => ele % 2); console.log(everyother)// 

Filter function can be simply we can code like this;

过滤功能可以简单的我们可以这样编码;

回答by anoNewb

const state.contactList = [{
name: 'jane',
email: '[email protected]'
},{},{},...]

const fileredArray = state.contactsList.filter((contactItem) => {
  const regex = new RegExp(`${action.payload}`, 'gi');
  return contactItem.nameProperty.match(regex) || contactItem.emailProperty.match(regex);
});


// contactList: all the contacts stored in state
// action.payload: whatever typed in search field