gpt4 book ai didi

JavaScript filter() 方法混淆

转载 作者:数据小太阳 更新时间:2023-10-29 04:06:06 25 4
gpt4 key购买 nike

作为 Learn JavaScript Properly 的一部分,我正在研究 JavaScript:权威指南 ,我在推理第 7 章数组方法部分的 filter() 方法时遇到了麻烦。

这是提供的示例:

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:

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]

我感到困惑的是 i 是如何应用到 everyother 行中的 x 的。这是我认为正在发生的事情:

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

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

当我在控制台乱七八糟时,我尝试过:

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

这是我所期望的,但我不明白当我将上面的代码更改为 JS 处理参数时内部发生了什么

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

(我知道数组方法是这样应用的:function(element, index, array))

对于这个特定的例子,对我来说很明显我可以用另一种方式得到预期的结果:

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

但我怀疑这种思路恰恰忽略了示例试图传达的要点......我只是错过了它。

最佳答案

你的例子非常简单明了:

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]

第一个是:»返回我小于 3 的每个元素 (x)«。结果并不令人吃惊。

第二个是:»返回索引 (i) 为偶数(包括 0)的每个元素«

x 被忽略了。

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

参见 MDN对于 Array.prototype.filter()

关于JavaScript filter() 方法混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25585353/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com