What’s the difference between “Array()” and “[]” while declaring a JavaScript array?

后端 未结 18 1466
生来不讨喜
生来不讨喜 2020-11-21 12:00

What\'s the real difference between declaring an array like this:

var myArray = new Array();

and

var myArray = [];
<         


        
18条回答
  •  醉话见心
    2020-11-21 12:46

    I can explain in a more specific way starting with this example that's based on Fredrik's good one.

    var test1 = [];
    test1.push("value");
    test1.push("value2");
    
    var test2 = new Array();
    test2.push("value");
    test2.push("value2");
    
    alert(test1);
    alert(test2);
    alert(test1 == test2);
    alert(test1.value == test2.value);
    

    I just added another value to the arrays, and made four alerts: The first and second are to give us the value stored in each array, to be sure about the values. They will return the same! Now try the third one, it returns false, that's because

    JS treats test1 as a VARIABLE with a data type of array, and it treats test2 as an OBJECT with the functionality of an array, and there are few slight differences here.

    The first difference is when we call test1 it calls a variable without thinking, it just returns the values that are stored in this variable disregarding its data type! But, when we call test2 it calls the Array() function and then it stores our "Pushed" values in its "Value" property, and the same happens when we alert test2, it returns the "Value" property of the array object.

    So when we check if test1 equals test2 of course they will never return true, one is a function and the other is a variable (with a type of array), even if they have the same value!

    To be sure about that, try the 4th alert, with the .value added to it; it will return true. In this case we tell JS "Disregarding the type of the container, whether was it function or variable, please compare the values that are stored in each container and tell us what you've seen!" that's exactly what happens.

    I hope I said the idea behind that clearly, and sorry for my bad English.

提交回复
热议问题