Possible Duplicate:
Access the first property of an object
I have a javascript object like this:
v开发者_C百科ar 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.
If I write the following code it returns undefined. Anybody knows how this can be done?
var first = list[0]; // this returns undefined
for(var key in obj) break;
// "key" is the first key here
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.
Even though some implementations of JavaScript uses lists to make object, they are supposed to be unordered maps.
So there is no first one.
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.
精彩评论