如何在javascript中添加(复制)数组内容到另一个数组而不替换数组的内容?

时间:2015-10-06 11:37:27

标签: javascript jquery

如何将数组的内容复制到另一个数组。

我有2个数组foo和bar,请看下面的内容:

foo = []   //this is a temp array which will be generated in a loop
bar = []

for(someCondition){
  for(someOtherCondition){
     foo = assignSomething;
  }
  // here I want the content of foo to be added to bar array and keep appending to the existing array
  //I tried bar.push(foo)  but this just creates an array of foo's but doesn't copy the foo array into bar array.
  //I also tried bar = foo.slice() but this just replaces the bar array everytime with new data
    }

感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

您可能想要使用Array原型的concat()方法。

https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array/concat

var alpha = ['a', 'b', 'c'],
    numeric = [1, 2, 3];

var alphaNumeric = alpha.concat(numeric);

console.log(alphaNumeric);

Browser compatibility

    Desktop Mobile 

Feature     Chrome  Firefox (Gecko)     Internet Explorer   Opera   Safari
Basic support   1.0     1.0 (1.7 or earlier)    5.5     (Yes)   (Yes)