获取对象的第一个索引 [英] Getting the first index of an object

查看:99
本文介绍了获取对象的第一个索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑:

var object = {
  foo: {},
  bar: {},
  baz: {}
}

我该怎么做:

var first = object[0];
console.log(first);

显然,这不起作用,因为第一个索引名为 foo
不是 0

Obviously, that doesn’t work because the first index is named foo, not 0.

console.log(object['foo']);

有效,但我不知道它的名字是foo。它可以被命名为任何东西。我只想要第一个。

works, but I don’t know it’s named foo. It could be named anything. I just want the first.

推荐答案

如果对象的顺序很重要,你应该修改你的JSON模式来存储对象在数组中:

If the order of the objects is significant, you should revise your JSON schema to store the objects in an array:

[
    {"name":"foo", ...},
    {"name":"bar", ...},
    {"name":"baz", ...}
]

或者可能:

[
    ["foo", {}],
    ["bar", {}],
    ["baz", {}]
]

正如Ben Alpert指出的那样,Javascript对象的属性是无序的,如果您希望它们按照它们在object literal - 没有first属性。

As Ben Alpert points out, properties of Javascript objects are unordered, and your code is broken if you expect them to enumerate in the same order that they are specified in the object literal—there is no "first" property.

这篇关于获取对象的第一个索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆