Emptying an array is a common JavaScript task but too often I see the task performed in the incorrect way. Many times developers will create a new array:
清空数组是常见JavaScript任务,但是我经常看到任务以错误的方式执行。 开发人员很多时候会创建一个新的数组:
myArray = []; // bad
That isn't the optimal way to get a fresh array; to truncate an array, and thus empty it, you should set the length property to zero:
这不是获得新阵列的最佳方法。 要截断数组并因此清空它,应将length属性设置为零:
myArray.length = 0; // good!
Setting the length equal to zero empties the existing array, not creating another array! This helps you to avoid pointer issues with arrays as well. With the new array method above:
将长度设置为零将清空现有数组,而不创建另一个数组! 这也可以帮助您避免数组出现指针问题。 使用上面的新数组方法:
// ... as provided by Dag in the comments
A = [1,2,3,4,5]
B = A
A = []
console.log(B) // [1,2,3,4,5]
The length
truncation would make both A
and B
the original array but empty!
length
截断会使A
和B
成为原始数组,但为空!