最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

language features - Is the order of fields in a javascript object predictable when looping through them? - Stack Overflow

programmeradmin4浏览0评论

In php, if you have the following code:

$map = array(
  "first" => 1,
  "second" => 2
);

$map["third"] = 3;

foreach($map as $key => $value) {
  // code
}

You know the entries will be listed in the order they have been added to the array.

Now, can I assume the same rule applies to the Javascript equivalent below?

map = {
  "first": 1,
  "second": 2
};

map["third"] = 3;

for (key in map) {
  // code
}

This is a duplicate of: Elements order - for (… in …) loop in javascript

In php, if you have the following code:

$map = array(
  "first" => 1,
  "second" => 2
);

$map["third"] = 3;

foreach($map as $key => $value) {
  // code
}

You know the entries will be listed in the order they have been added to the array.

Now, can I assume the same rule applies to the Javascript equivalent below?

map = {
  "first": 1,
  "second": 2
};

map["third"] = 3;

for (key in map) {
  // code
}

This is a duplicate of: Elements order - for (… in …) loop in javascript

Share Improve this question edited May 23, 2017 at 12:08 CommunityBot 11 silver badge asked Mar 15, 2009 at 17:01 Julian AubourgJulian Aubourg 11.4k1 gold badge30 silver badges29 bronze badges 1
  • possible duplicate of Elements order - for (... in ...) loop in javascript – Borgar Commented Jun 7, 2011 at 19:36
Add a ment  | 

2 Answers 2

Reset to default 10

Most browsers will loop through the properties in the order they were added to the object, but the Javascript standard says the order is undefined -- so you shouldn't rely on this behavior. For example, I read a blog post a while back about how Google Chrome didn't always exhibit this behavior.

If you need the ordered functionality, you should create a new class for yourself that can use both object or numeric keys.

No, the behavior depends on implementation and it is not guaranteed. Use an array when the order needs to be preserved.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论