concat和push之间的区别? [英] Difference between concat and push?

查看:43
本文介绍了concat和push之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么返回push方法会导致Uncaught TypeError:acc.push不是函数。但是返回concat会产生正确的解决方案吗?

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?

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

推荐答案

push()将元素添加到数组的末尾并返回数组的新长度。因此,此处的返回无效。

The push() adds elements to the end of an array and returns the new length of the array. Thus your return here is invalid.

concat()方法用于合并数组。 Concat不会更改现有数组,而是返回一个新数组。

The concat() method is used to merge arrays. Concat does not change the existing arrays, but instead returns a new array.

最好过滤,如果你想要一个像这样的新数组:

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

注意假设数组arr完整且没有间隙 - 所有甚至是索引值。如果您需要每个人,请使用元素而不是 index

Note that assumes the array arr is complete with no gaps - all even indexed values. If you need each individual, use the element instead of index

var arr = [1, 2, 3, 4];
var filtered = arr.filter(function(element, index, array) {
  return (element% 2 === 0);
});

这篇关于concat和push之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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