简体   繁体   English

JavaScript对象文字和数组文字

[英]JavaScript Object Literals & Array Literals

What is the difference between Object Literals and Array Literals in JavaScript? JavaScript中的Object Literals和Array Literals有什么区别? I know it has something to do with the length method but i don't fully understand it. 我知道它与长度方法有关但我不完全理解它。

Mozilla.org has very good explanation of the different literals with examples. Mozilla.org通过示例对不同的文字进行了非常好的解释。

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. 这将导致错误或不按预期运行,因为{将被解释为块的开头。

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 数组采用数字索引,顺序完全可靠

Object literal 对象文字

var a = {};

Array Literal Array Literal

var a = [];

That's it! 而已!

PHP's numeric array becomes an array literal or object literal in JavaScript PHP的数字数组在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 PHP的关联数组成为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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM