JavaScript 数组大括号与方括号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5129544/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript arrays braces vs brackets
提问by Pinkie
What is the difference between each of the following array definitions.
以下每个数组定义之间有什么区别。
var myArray = [];
var myArray = {};
var myArray = new Array();
回答by johusman
The first and third are equivalent and create a new array. The second creates a new empty object, not an array.
第一个和第三个是等效的,并创建一个新数组。第二个创建一个新的空对象,而不是一个数组。
var myArray = []; //create a new array
var myArray = {}; //creates **a new empty object**
var myArray = new Array(); //create a new array
回答by leepowers
var myObject = {};
is equivalent to var myObject = new Object();
var myObject = {};
相当于 var myObject = new Object();
So, the second example is not an Array
but a general Object
.
因此,第二个示例不是 anArray
而是一般Object
.
This can get confusing as Array
is a class and Object
is a class - more precisely Array
is a sub-class of Object
. So, by and large, Object
semantics are applicable to an Array
:
这可能会让人感到困惑,因为它Array
是一个类并且Object
是一个类 - 更准确地说Array
是Object
. 因此,总的来说,Object
语义适用于Array
:
var o = [];
o.push('element1');
o.push('element2');
o['property1'] = 'property value'; // define a custom property.
console.log(o.property1);
console.log(o.length); // Outputs '2' as we've only push()'ed two elements onto the Array