Javascript 如何在javascript中获取对象的第一个成员
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7545209/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get first member of an object in javascript
提问by Mo Valipour
Possible Duplicate:
Access the first property of an object
可能的重复:
访问对象的第一个属性
I have a javascript object like this:
我有一个这样的 javascript 对象:
var list = {
item1: "a",
item2: "b",
item3: "c",
item4: "d"
};
Using reflection in JS, I can say list["item1"] to get or set each member programmatically, but I don't want to rely on the name of the member (object may be extended). So I want to get the first member of this object.
在 JS 中使用反射,我可以说 list["item1"] 以编程方式获取或设置每个成员,但我不想依赖成员的名称(对象可能会被扩展)。所以我想得到这个对象的第一个成员。
If I write the following code it returns undefined. Anybody knows how this can be done?
如果我编写以下代码,它将返回未定义。有谁知道如何做到这一点?
var first = list[0]; // this returns undefined
回答by user187291
for(var key in obj) break;
// "key" is the first key here
回答by Petar Ivanov
var list = {
item1: "a",
item2: "b",
item3: "c",
item4: "d"
};
is equivalent to
相当于
var list = {
item2: "b",
item1: "a",
item3: "c",
item4: "d"
};
So there is no first element. If you want first element you should use array.
所以没有第一个元素。如果你想要第一个元素,你应该使用数组。
回答by megakorre
Even though some implementations of JavaScript uses lists to make object, they are supposed to be unordered maps.
尽管 JavaScript 的一些实现使用列表来创建对象,但它们应该是无序映射。
So there is no first one.
所以没有第一个。
回答by Hyman
How do I loop through or enumerate a JavaScript object?
You can use the following to get the desired key.
您可以使用以下方法获取所需的密钥。
for (var key in p) {
if (p.hasOwnProperty(key)) {
alert(key + " -> " + p[key]);
}
}
You need to use an array if you want to access elements in an indexed way.
如果要以索引方式访问元素,则需要使用数组。