简体   繁体   English

JavaScript:为什么我不能将 Array.prototype.filter 与.push() 链接在一起?

[英]JavaScript: why can't I chain Array.prototype.filter with .push()?

If Array.prototype.filter returns an array, why can't I invoke push() on this return value immediately?如果Array.prototype.filter返回一个数组,为什么我不能立即对这个返回值调用push()

Example:例子:

var arr = ["a", "ab", "c", "ad"];
var arr2 = arr.filter(function(elmnt) { return elmnt.indexOf("a") > -1; });
// result: ["a", "ab", "ad"]

arr2.push("aaa");
// result: ["a", "ab", "ad", "aaa"]

Ok so far.好的到目前为止。

But what about chaining that push() call to the filter() call?但是如何将push()调用链接到filter()调用呢?

var arr = ["a", "ab", "c", "ad"];
var arr2 = arr.filter(function(elmnt) { return elmnt.indexOf("a") > -1; }).push("aaa");
// result: 4

Why does chaining filter() and push() result in the number of elements that I would expect, rather than an array of those elements?为什么链接filter()push()会产生我期望的元素数量,而不是这些元素的数组?

The problem is not with what filter() returns, instead it is with what push() returns. 问题不在于filter()返回什么,而是与push()返回的内容有关。

push() returns the new length of the array, and not the array itself. push()返回数组的新长度,而不是数组本身。

So when you do: 所以当你这样做时:

var arr2 = arr.filter(function(elmnt) { return elmnt.indexOf("a") > -1; }).push("aaa");

arr2 will be assigned the new length of the array (which happens to be 4 in your case), and not the new array as such. 将为arr2分配数组的新长度(在您的情况下恰好为4),而不是新数组。

A modified version that'll do what you want would be: 一个可以做你想做的修改版本:

var arr = ["a", "ab", "c", "ad"], arr2;
(arr2 = arr.filter(function(elmnt) { return elmnt.indexOf("a") > -1; })).push("aaa");
// now arr2 is ["a", "ab", "ad", "aaa"]

I suggest you use concat(); 我建议你使用concat();

var arr = ["a", "ab", "c", "ad"], arr2;
(arr2 = arr.filter(function(elmnt) { return elmnt.indexOf("a") > -1; })).concat("aaa");
// now arr2 is ["a", "ab", "ad", "aaa"]

now run the above code and see the result/error.现在运行上面的代码并查看结果/错误。

Analyze the difference between your answer before and after running the code分析运行代码前后你的答案的区别

Q2. Q2。 correct the code so that method chain starts working更正代码以便方法链开始工作

function filterOddNumbers(num) {
    if (num % 2 === 0) {
        return true;
    } else {
        return false;
    }
}

const evenNumbers = [1, 2, 3, 4, 5].push().filter(filterOddNumbers);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM