开发者

How to get first member of an object in javascript [duplicate]

开发者 https://www.devze.com 2023-04-07 15:46 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: Access the first property of an object
This question already has answers here: Closed 11 years ago.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消