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

Popular posts from this blog

facebook - android ACTION_SEND to share with specific application only -

python - Creating a new virtualenv gives a permissions error -

javascript - cocos2d-js draw circle not instantly -