Difference between Array.length = 0 and Array =[]?

前端 未结 3 2200
无人及你
无人及你 2020-11-29 20:47

Can some one explain the conceptual difference between both of them. Read somewhere that the second one creates a new array by destroying all references to the existing arra

相关标签:
3条回答
  • 2020-11-29 21:30

    foo = [] creates a new array and assigns a reference to it to a variable. Any other references are unaffected and still point to the original array.

    foo.length = 0 modifies the array itself. If you access it via a different variable, then you still get the modified array.

    Read somewhere that the second one creates a new array by destroying all references to the existing array

    That is backwards. It creates a new array and doesn't destroy other references.

    var foo = [1,2,3];
    var bar = [1,2,3];
    var foo2 = foo;
    var bar2 = bar;
    foo = [];
    bar.length = 0;
    console.log(foo, bar, foo2, bar2);
    

    gives:

    [] [] [1, 2, 3] []
    

    arr.length =0;// expected to empty the array
    

    and it does empty the array, at least the first time. After the first time you do this:

    arr = arr + $(this).html();
    

    … which overwrites the array with a string.

    The length property of a string is read-only, so assigning 0 to it has no effect.

    0 讨论(0)
  • 2020-11-29 21:36

    The difference here is best demonstrated in the following example:

    var arrayA = [1,2,3,4,5];
    
    function clearUsingLength (ar) {
        ar.length = 0;
    }
    
    function clearByOverwriting(ar) {
        ar = [];
    }
    
    alert("Original Length: " + arrayA.length);
    clearByOverwriting(arrayA);
    alert("After Overwriting: " + arrayA.length);
    clearUsingLength(arrayA);
    alert("After Using Length: " + arrayA.length);
    

    Of which a live demo can be seen here: http://www.jsfiddle.net/8Yn7e/

    When you set a variable that points to an existing array to point to a new array, all you are doing is breaking the link the variable has to that original array.

    When you use array.length = 0 (and other methods like array.splice(0, array.length) for instance), you are actually emptying the original array.

    0 讨论(0)
  • 2020-11-29 21:39

    Are you sure it really works?

    I did a little experiment here, and trying to "add" an Array with a String resulted in a string.

    function xyz(){
        var a = [];
        alert(typeof(a+$("#first").html()));
        // shows "string"
    }
    

    http://www.jsfiddle.net/4nKCF/

    (tested in Opera 11)

    0 讨论(0)
提交回复
热议问题