Array.prototype.push.应用意外行为

Array.prototype.push.apply unexpected behaviour

本文关键字:意外 应用 prototype push Array      更新时间:2023-09-26

我正在尝试使用Array.prototype.push.apply来合并两个列表。

c = Array.prototype.push.apply(a, b);

但是,当第二个数组是[]时,这不会合并数组。

例如,如果

a = ['x', 'y', 'z']
b = []

c将是3

为什么会发生这种情况?[]不应该像对待任何数组一样对待吗?

只需使用Array.prototype.concat:

c = a.concat(b);
这是完全正确的,因为Array.push()将返回新数组的长度。

如果您想要一个具有串联值的新数组,请改用array.concat()。

您可能试图实现的是使用push.applyb附加到a。但是,这种方法意味着您不必创建新的数组c来保存结果。

var a = [1, 2, 3, 4], b = [5];
a.push.apply(a, b); // a = [1, 2, 3, 4, 5]

您真正的问题是.apply,它询问contetx(a)和一个值数组(b),如果您传递一个空数组,它的行为就像您没有传递任何值。。。

试试这个:

c = Array.prototype.push.call(a, b);
//c = 4