简体   繁体   中英

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?

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(); you are saying it has all the properties and attributes of an array like length for example. If you are not intending to use it as a true array ( pop , push , length , etc.) then don't use a JavaScript array.

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';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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