JavaScript Object Literals & Array Literals

前端 未结 4 1255
忘了有多久
忘了有多久 2020-12-03 08:38

What is the difference between Object Literals and Array Literals in JavaScript? I know it has something to do with the length method but i don\'t fully understand it.

相关标签:
4条回答
  • 2020-12-03 08:49

    Object literal

    var a = {};
    

    Array Literal

    var a = [];
    

    That's it!

    0 讨论(0)
  • 2020-12-03 08:50

    The difference is the way they're indexed.
    Objects have name, value pairs which are not ordered. In some browsers the order you added values will be the order you get when you traverse the object but not in all. The name is usually a string.
    Arrays are numerically indexed and the order is totally reliable

    0 讨论(0)
  • 2020-12-03 08:51

    PHP's numeric array becomes an array literal or object literal in JavaScript

    $ar = array('apple', 'orange', 'banana', 'strawberry');
    
    echo json_encode($ar); // ["apple","orange","banana","strawberry"] - Array literal
    
    echo json_encode($ar, **JSON_FORCE_OBJECT**); // {"0":"apple","1":"orange","2":"banana","3":"strawberry"} - Object Literal
    

    PHP's associative array becomes an object literal in JavaScript

    $book = array(
             "title" => "JavaScript: The Definitive Guide",
             "author" => "David Flanagan",
             "edition" => 6
            );
    
    echo json_encode($book); // {title: "JavaScript: The Definitive Guide", author: "David Flanagan", edition: 6} - Object Literal
    
    0 讨论(0)
  • 2020-12-03 09:02

    Mozilla.org has very good explanation of the different literals with examples.

    Array Literals

    An array literal is a list of zero or more expressions, each of which represents an array element, enclosed in square brackets ([]). When you create an array using an array literal, it is initialized with the specified values as its elements, and its length is set to the number of arguments specified.

    Object Literals

    An object literal is a list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ({}). You should not use an object literal at the beginning of a statement. This will lead to an error or not behave as you expect, because the { will be interpreted as the beginning of a block.

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