Javascript 连接和推送的区别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44572026/
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
Difference between concat and push?
提问by The cows are in the Meadow
Why does a return of the push method cause "Uncaught TypeError: acc.push is not a function". But a return concat results in the correct solution?
为什么 push 方法的返回会导致“Uncaught TypeError: acc.push is not a function”。但是返回 concat 会导致正确的解决方案?
[1, 2, 3, 4].reduce(function name(acc, curr) {
if (even(curr)) {
return acc.push(curr);
}
return acc;
}, []);
function even(number) {
if (number % 2 === 0) {
return true;
}
return false;
}
[1, 2, 3, 4].reduce(function name(acc, curr) {
if (even(curr)) {
return acc.concat(curr);
}
return acc;
}, []);
function even(number) {
if (number % 2 === 0) {
return true;
}
return false;
}
回答by Mark Schultheiss
The push()adds elements to the end of an array and returns the new length of the array. Thus your return here is invalid.
所述push()添加元素添加到数组的末尾,并返回该数组的新长度。因此,您在此处的返回无效。
The concat()method is used to merge arrays. Concat does not change the existing arrays, but instead returns a new array.
该concat()方法用于合并数组。Concat 不会更改现有数组,而是返回一个新数组。
Better to filter, if you want a NEW array like so:
更好地过滤,如果你想要一个像这样的新数组:
var arr = [1, 2, 3, 4];
var filtered = arr.filter(function(element, index, array) {
return (index % 2 === 0);
});
Note that assumes the array arr is complete with no gaps - all even indexed values. If you need each individual, use the elementinstead of index
请注意,假设数组 arr 是完整的,没有间隙 - 所有偶数索引值。如果您需要每个人,请使用element代替index
var arr = [1, 2, 3, 4];
var filtered = arr.filter(function(element, index, array) {
return (element% 2 === 0);
});
回答by Karl Reid
accshould not be an array. Look at the documentation. It canbe one, but..
acc不应该是一个数组。查看文档。它可以是一个,但是..
It makes no sense at all to reducean array to an array. What you want is filter. I mean, reduceusing an array as the accumulator and concating each element to it technically does work, but it is just not the right approach.
reduce数组到数组完全没有意义。你想要的是filter. 我的意思是,reduce使用数组作为累加器并将concat每个元素放入它在技术上确实可行,但这不是正确的方法。
var res = [1, 2, 3, 4].filter(even);
console.log(res);
function even(number) {
return (number % 2 === 0);
}
回答by shiv garg
https://dev.to/uilicious/javascript-array-push-is-945x-faster-than-array-concat-1okiConcat is 945x slower than push only because it has to create a new array.
https://dev.to/uilicious/javascript-array-push-is-945x-faster-than-array-concat-1okiConcat 比 push 慢 945 倍,仅因为它必须创建一个新数组。

