Difference between create a new Array and clear the length

This question already has an answer here:

  • Difference between Array.length = 0 and Array =[]? 3 answers
  • How do I empty an array in JavaScript? 18 answers

  • There is quite a big difference between just using [] and .length = 0 .

    If you use = [] you will assign a new reference to the variable, losing your reference to the original, by using .length = 0 you will clear the original array, leaving the original reference intact.


    With array = new Array(); you will create a new reference.

    A better way to clear an array and keep the reference would be:

    var array = [1,2,3,4,5];
    
    while (array.length) {
        array.pop();
    }
    

    Also take a look at this exact same question: Difference between Array.length = 0 and Array =[]?

    链接地址: http://www.djcxy.com/p/23948.html

    上一篇: 你将如何从数组中删除所有对象?

    下一篇: 创建一个新的Array并清除长度之间的区别