简体   繁体   English

将关联数组声明为新Array()是否与将关联数组声明为对象{}相同?

[英]Is declaring an associative array as a new Array() the same as declaring an associative array as an object {}?

Is the object whiteStripes the same exact thing in both cases? 在这两种情况下,对象whiteStripes是否完全相同?

var whiteStripes = {'Jack' : 'White', 'Meg' : 'White'};

var whiteStripes = new Array();
whiteStripes['Jack'] = 'White';
whiteStripes['Meg'] = 'White';

While you will still be able to access the properties the same way ( whiteStripes['Jack'] ) in both instances when you declare whiteStripes = new Array(); 当您声明whiteStripes = new Array();仍然可以在两种情况下以相同的方式访问属性( whiteStripes['Jack'] whiteStripes = new Array(); you are saying it has all the properties and attributes of an array like length for example. 您是说它具有数组的所有属性和属性,例如length If you are not intending to use it as a true array ( pop , push , length , etc.) then don't use a JavaScript array. 如果您不打算将其用作真正的数组( poppushlength等),则不要使用JavaScript数组。

No, it's not the exact same thing. 不,这不是一回事。

Both will work, because an array is also an object, but if you want just an object you should not create an array to get one. 两者都可以工作,因为数组也是一个对象,但是如果只需要一个对象,则不应创建一个数组来获取一个对象。

These would result in the exact same thing being created: 这些将导致创建完全相同的事物:

var whiteStripes = {'Jack' : 'White', 'Meg' : 'White'};

var whiteStripes = new Object();
whiteStripes['Jack'] = 'White';
whiteStripes['Meg'] = 'White';

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

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