如何在javascript中连接两个数组? [英] how can I concatenate two arrays in javascript?
问题描述
我看到了回复用另一个
扩展一个数组,所以我尝试了:
I saw this response for extending one array with another so I tried:
console.log(['a', 'b'].push.apply(['c', 'd']));
但它会打印:
2
不应该打印:
['a', 'b', 'c', 'd']
如果不是我做错了什么?
if not what was i doing wrong?
推荐答案
如果不是我做错了什么?
if not what was i doing wrong?
首先, .push
返回数组的新长度:
var arr = [1, 1, 1];
console.log(arr.push(1)); // 4
console.log(arr); // [1, 1, 1, 1]
其次, .apply
需要两个参数:要将函数应用于的对象,以及参数数组。您只传递一个参数,因此您的代码基本上等同于:
Second, .apply
needs two arguments: The object you want to apply the function to, and an array of arguments. You only pass a single argument, so your code is basically equivalent to:
['c', 'd'].push()
即你没有在 ['c','d']
数组中添加任何内容。这也解释了为什么你在输出中看到 2
: ['c','d']
的长度 2
和 .push()
不会向其添加任何元素,因此它的长度仍为 2
。
I.e. you are not adding anything to the ['c', 'd']
array. That also explains why you see 2
in the output: ['c', 'd']
has length 2
and .push()
doesn't add any elements to it so it still has length 2
.
如果您想使用 .push
来改变原始数组(而不是创建一个新的,如 .concat
确实如此),它必须如下所示:
If you want to use .push
to mutate the original array (instead of creating a new one like .concat
does), it would have to look like:
var arr = ['a', 'b'];
arr.push.apply(arr, ['c', 'd']); // equivalent to Array.prototype.push.apply(arr, [...])
// ^ ^--------^
// apply to arr arguments
console.log(arr); // ['a', 'b', 'c', 'd']
参见
See also
- How to append something to an array?
- Javascript push array values into another array
这篇关于如何在javascript中连接两个数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!