Copying array by value in JavaScript -
when copying array in javascript array:
var arr1 = ['a','b','c']; var arr2 = arr1; arr2.push('d'); //now, arr1 = ['a','b','c','d']
i realized arr2
refers same array arr1
, rather new, independent array. how can copy array 2 independent arrays?
use this:
var newarray = oldarray.slice();
basically, slice() operation clones array , returns reference new array. note that:
for references, strings , numbers (and not actual object), slice copies object references new array. both original , new array refer same object. if referenced object changes, changes visible both new , original arrays.
primitives such strings , numbers immutable changes string or number impossible.
Comments
Post a Comment