I want to replace all values ​​with other array values, both arrays are the same size

eg:

var Array1=array(1,2,3,4,5,6);
var Array2=array(7,8,9,10,11,12);

      

after replacement Array2

from the Array1

values ​​of the resulting array should be

var Array1=array(7,8,9,10,11,12);

      

+5


source to share


4 answers


Use slice

:

Array1 = Array2.slice(0);

      



This will take a copy Array2

, not a link to it, so if you make changes to Array2

, they won't show up in Array1

.

DEMO

+15


source


Before ES6:

Array1.length = 0;                  // Clear contents
Array1.push.apply(Array1, Array2);  // Append new contents

      



ES6 post:

Array1.splice(0, Array1.length, ...Array2);

      

+10


source


With a for loop:

var Array1=[1,2,3,4,5,6];
var Array2=[7,8,9,10,11,12];
for (var i = 0; i < Array1.length; i++){
  Array1[i] = Array2[i]
}
console.log(Array1)

      

0


source


As mentioned here , there are many ways to duplicate an array.

Above is the slice.

There is also a concat method . http://jsfiddle.net/zto56a52/

 var Array1=[1,2,3,4,5,6];
    var Array2=[7,8,9,10,11,12];
    Array1 = [].concat(Array2); 
    alert(Array1);

      

-4


source







All Articles