在JS对象数组中,我应该使用键来识别每个对象吗?

时间:2021-11-16 00:46:58

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"
},
...
]

1 个解决方案

#1


1  

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". 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.

在Javascript中,您可以选择数组,这些数组已经过排序,但基本上是“少关键”。每个数组条目只能通过其数字索引句点访问。另一个选项是对象,它们没有保证顺序但是由任意值键入。

['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.)

(注意:虽然您可以对数组使用任意数字索引,但是您不能使用文字语法[..],并且它通常不是一个好主意。如果您需要显式键,则需要对象。)

#1


1  

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". 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.

在Javascript中,您可以选择数组,这些数组已经过排序,但基本上是“少关键”。每个数组条目只能通过其数字索引句点访问。另一个选项是对象,它们没有保证顺序但是由任意值键入。

['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.)

(注意:虽然您可以对数组使用任意数字索引,但是您不能使用文字语法[..],并且它通常不是一个好主意。如果您需要显式键,则需要对象。)