javascript 不使用concat方法添加两个数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5240335/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 16:29:02  来源:igfitidea点击:

Add two arrays without using the concat method

javascript

提问by qw3n

Here is a sample of what I would like to do

这是我想做的示例

function test(r){
  var arr = ['d','e','f'];
  r.push(arr);
  /*
  More Code
  */
  return r;
}
var result = test(['a','b','c']);
alert(result.length);//I want this to alert 6

What I need to do is pass in an array and attach other arrays to the end of it and then return the array. Because of passing by reference I cannot use array.concat(array2);. Is there a way to do this without using something like a for loop to add the elements one by one. I tried something like r.push(arr.join());but that did not work either. Also, I would like the option of having objects in the arrays so really the r.push(arr.join());doesn't work very well.

我需要做的是传入一个数组并将其他数组附加到它的末尾,然后返回该数组。由于通过引用传递,我无法使用array.concat(array2);. 有没有办法在不使用 for 循环之类的东西一个一个地添加元素的情况下做到这一点。我试过类似的东西,r.push(arr.join());但也没有奏效。另外,我想要在数组中包含对象的选项,因此实际上r.push(arr.join());效果不佳。

回答by emulbreh

>>> var x = [1, 2, 3], y = [4, 5, 6];
>>> x.push.apply(x, y) // or Array.prototype.push.apply(x, y)
>>> x
[1, 2, 3, 4, 5, 6]

Alternatively using destructuringyou can now do this

或者使用解构,你现在可以做到这一点

//generate a new array
a=[...x,...y];
//or modify one of the original arrays
x.push(...y);

回答by mVChr

function test(r){
  var _r = r.slice(0), // copy to new array reference
      arr = ['d','e','f'];

  _r = _r.concat(arr); // can use concat now

  return _r;
}
var result = test(['a','b','c']);
alert(result.length); // 6

回答by meouw

This is emulbreh's answer, I'm just posting the test I did to verify it. All credit should go to emulbreh

这是emulbreh 的回答,我只是发布了我为验证所做的测试。所有的功劳都应该归功于 emulbreh

// original array
var r = ['a','b','c'];

function test(r){
  var arr = ['d','e','f'];
  r.push.apply(r, arr);

  /*
  More Code
  */
  return r;
}
var result = test( r );
console.log( r ); // ["a", "b", "c", "d", "e", "f"]
console.log( result === r ); // the returned array IS the original array but modified