[英]In a JS array of objects, should I use a keys to identify each object?
I'm still learning javascript patterns, and I'm curious about this one. 我仍在学习javascript模式,对此感到很好奇。
If I have an array of objects, should I make the array of objects not have keys (Example A), or use their keys (Example B)? 如果我有一个对象数组,是否应该使对象数组没有键(示例A),或者使用其键(示例B)?
An array of objects without any key: 没有任何键的对象数组:
var soylent_green_candidates = [{
id: 12341,
name: "Don",
gender: "Male",
weapon_of_choice: "Kangaroo Cannon"
},
{
id: 24325,
name: "Jimmy",
gender: "Male",
weapon_of_choice: "Sushi Blaster"
},
...
]
Or an array of objects using the unique ID's as keys: 或使用唯一ID作为键的对象数组:
var soylent_green_candidates = [
12341: {
name: "Don",
gender: "Male",
weapon_of_choice: "Kangaroo Cannon"
},
24325: {
name: "Jimmy",
gender: "Male",
weapon_of_choice: "Sushi Blaster"
},
...
]
Your second example is invalid, so that should put the question to sleep. 您的第二个示例是无效的,因此应该将问题搁浅。
In Javascript you have the option of arrays , which are sorted but essentially "key less". 在Javascript中,您可以选择数组 ,这些数组经过排序,但本质上是“少键”。 Each array entry can only be accessed by its numeric index, period. 每个数组条目只能通过其数字索引句点来访问。
The other option is objects , which have no guaranteed order but are keyed by arbitrary values. 另一个选项是object ,它们没有保证的顺序,但由任意值键入。
['foo', 'bar', 'baz']
{ foo : 'bar', baz : 42 }
You make the choice based on these two criteria, order and requirement for keys. 您基于这两个标准(密钥的顺序和要求)进行选择。
(Note: while you can use arbitrary numeric indices for arrays, you can't do so using the literal syntax [..]
, and it's not usually a good idea. If you need explicit keys, you want objects.) (注意:虽然可以对数组使用任意数字索引,但不能使用文字语法[..]
这样做,通常不是一个好主意。如果需要显式键,则需要对象。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.