不使用concat方法添加两个数组 [英] Add two arrays without using the concat method

查看:185
本文介绍了不使用concat方法添加两个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我想做的事情的示例

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

我是什么需要做的是传入一个数组并将其他数组附加到它的末尾,然后返回该数组。由于通过引用传递,我不能使用 array.concat(array2); 。有没有办法做到这一点,而不使用像for循环这样的东西逐个添加元素。我试过像 r.push(arr.join()); 这样的东西,但那也没办法。另外,我想在数组中有对象的选项,所以 r.push(arr.join()); 不能很好地工作。

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.

推荐答案

>>> 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]

或者使用< a href =https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment =noreferrer> destructuring 你现在可以做到这一点

Alternatively using destructuring you can now do this

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

这篇关于不使用concat方法添加两个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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