Use Array.length
to set a new size for an array, which is faster than Array.splice
to mutate:
var array = ['mario','luigi','kong', 1, 3, 6, 8];
array.length=2;
alert(array); // shows "mario,luigi";
Why is it faster? Because .splice
has to create a new array containing all the removed items, whereas .length
creates nothing and "returns" a number instead of a new array.
To address .splice
usage, you can feed it a negative index, along with a huge number to chop off the end of an array:
var array = ['mario','luigi','kong'];
array.splice(-1, 9e9);
alert(array); // shows "mario,luigi";
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…