Short way to replace content of an array
What about this:
// 1. reset the array while keeping its reference
arr1.length = 0;
// 2. fill the first array with items from the second
[].push.apply(arr1, arr2);
See:
- How to empty an array in JavaScript?
- .push() multiple objects into JavaScript array returns 'undefined'
You can use splice to replace the content of arr1
with the one of arr2
:
[].splice.apply(arr1, [0, arr1.length].concat(arr2));
This way, all references to arr1
would be correctly updated as this would be the same array with a new content.
As you see, that's possible and easy. But there's normally no reason to do this in a well designed program. If the reason is that you're passing an array to different places, then perhaps you should consider embedding this array in an object.