839Empty an Array, but Preserve it’s Association
Creating an array 'a', creating an association from 'b' to 'a'.
var a = [1,2,3,4];
var b = a;
console.log(a); // [1,2,3,4]
console.log(b); // [1,2,3,4]
But what happens, when I want to empty the array using the 'b' variable? The first obvious attempt would be to assign a new, empty array to 'b'.
b = [];
console.log(a); // [1,2,3,4]
console.log(b); // [] NG!
Hmmm. Something's not quite right here. By assigning a new, empty array to 'b' we also lost our association with the 'a' array.
How can we keep the association and empty the array? T
b.length = 0 ;
b.push(1);
b.push(2);
b.push(3);
b.push(4);
console.log(a); // [1,2,3,4]
console.log(b); // [1,2,3,4] OK!
There is also a slightly different way using splice.
b.splice(0, b.length);
b.push(1);
b.push(2);
b.push(3);
b.push(4);
console.log(a); // [1,2,3,4]
console.log(b); // [1,2,3,4] OK!
In case you wonder, where this can be useful. Let's assume you have a global object and somewhere in it there's an array you want to do something with.
var myGlobalObj = {};
myGlobalObj.reallyLong = {};
myGlobalObj.reallyLong.andAnnoying = [];
var testFunction = function() {
var sweet = myGlobalObj.reallyLong.andAnnoying; // associate
sweet.length = 0; // empty sweet & myGlobalObj.reallyLong.anAnnoying Array
}