Problem with assign array to tmpArr?


#1

I would like to assign array to tmpArr

var arr = [1, 2, 3];
var tmpArr = arr;
tmpArr.push(4);

arr [1, 2, 3, 4] // why? I don't understand.

Could help me.


#2

Hi,

var arr = [1, 2, 3];
var tmpArr = _.clone(arr);
tmpArr.push(4);
console.log(arr, tmpArr); // [1,2,3] [1,2,3,4]

#3

Look great, Thanks again :smiley:


#4

It’s because your are copying the address where the array is located in memory, not the array itself.


#5

Or with vanilla JS :
var tmpArr = [].slice.call(arr);

Or with ES6 :

let tmpArr =  Array.from(arr);