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
2 Answers
Reset to default 10Most 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.