What’s the difference between “{}” and “[]” while declaring a JavaScript array?

前端 未结 7 2146
半阙折子戏
半阙折子戏 2020-12-02 10:04

What’s the difference between “{}” and “[]” while declaring a JavaScript array? Normally I declare like

var a=[];

What is the meaning of de

7条回答
  •  不知归路
    2020-12-02 10:15

    In JavaScript Arrays and Objects are actually very similar, although on the outside they can look a bit different.

    For an array:

    var array = [];
    array[0] = "hello";
    array[1] = 5498;
    array[536] = new Date();
    

    As you can see arrays in JavaScript can be sparse (valid indicies don't have to be consecutive) and they can contain any type of variable! That's pretty convenient.

    But as we all know JavaScript is strange, so here are some weird bits:

    array["0"] === "hello"; // This is true
    array["hi"]; // undefined
    array["hi"] = "weird"; // works but does not save any data to array
    array["hi"]; // still undefined!
    

    This is because everything in JavaScript is an Object (which is why you can also create an array using new Array()). As a result every index in an array is turned into a string and then stored in an object, so an array is just an object that doesn't allow anyone to store anything with a key that isn't a positive integer.

    So what are Objects?

    Objects in JavaScript are just like arrays but the "index" can be any string.

    var object = {};
    object[0] = "hello"; // OK
    object["hi"] = "not weird"; // OK
    

    You can even opt to not use the square brackets when working with objects!

    console.log(object.hi); // Prints 'not weird'
    object.hi = "overwriting 'not weird'";
    

    You can go even further and define objects like so:

    var newObject = {
        a: 2,
    };
    newObject.a === 2; // true
    

提交回复
热议问题