I have learned from somewhere that if I have a unordered collection (eg. a list of things to buy) I should use an object literal in Javascript. And if I have an ordered list (eg. a list of things to buy in prioritized order) I should use an array.
Array:
priorityList = [
"computer"
"mouse"
"pen"
]
My question is how could this be done with an object literal? And is it correct that I should use objects for unordered lists, or should I use arrays for it as well?
UPDATE to one of 开发者_如何学Gothe answer:
Choice 1:
var things = [
{"name":"computer","price":300},
{"name":"mouse","price":20},
];
Choice 2:
var things = {
"computer": {
"price": 300
},
"mouse": {
"price": 20
}
}
Which one should I choose?
UPDATE 2 to one of the answer:
var ulist = {
"bar": {
"price": 12
},
"baz": {
"price": 12
},
"bar": {
"price": 12
}
}
for(item in ulist) {
console.log(item); // bar baz
}
var olist = [
{"name": "bar"},
{"name": "baz"},
{"name": "bar"}
]
console.log(olist[0].name); // bar
console.log(olist[1].name); // baz
console.log(olist[2].name); // bar
Here we see that unordered list where all items should be unique is good with Choice 2 cause even if I mistakenly provided multiple unique items it gets only one of them, and it doesn't care about orders.
But in choice 1 even if I have identical items they are treated as separate items and all are printed out. And it also seems that it's ordered cause there is no way to get an item without iterating it with [0], [1], [2] etc.
Does this prove that choice 2 is better for when you want to have unique items?
It's more about the complexity of the data structure. If you have a list of primitive things such as strings, use an array ( whether it's ordered or not ). If you have more complex data structure which requires key/value pairs, use an object literal.
If you are storing metadata, for example:
var things = [
{"name":"computer","price":300},
{"name":"mouse","price":20},
];
An array wouldn't suffice because I have lots of information stored in each object... but I keep them as children of an array. So if you are going to store more information than just the item itself, use object literals.
If you have an associative array-like structure, use an object literal as well:
var person = {
age: 23,
walk: function(){},
name: "john"
};
精彩评论