JavaScript array.forEach 是否按升序遍历元素 [英] Does JavaScript array.forEach traverse elements in ascending order

查看:21
本文介绍了JavaScript array.forEach 是否按升序遍历元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 JavaScript 中,我可以有一个带孔的数组:

In JavaScript I can have an array with holes:

a = [];
a[0] = 100;
a[5] = 200;
a[3] = 300;

a.forEach(function(x) {alert(x);});

我找不到有关是否按升序处理元素的信息,或者这不是可靠的事实.

I could not find information about whether elements would be processed in ascending order or this is not reliable fact.

我检查了for .. in"循环以升序遍历数组索引,而对象的属性名称以它们添加到对象的相同顺序遍历(至少看起来如此).

I checked that "for .. in" loop traverses array indices in ascending order, while property names of an object are traversed in the same order they were added to object (at least it looks so).

(即看起来数组是某种内部树,而对象是哈希表.)

(I.e. it looks like arrays are internally trees of some kind and objects are hashtables.)

我刚刚发现 Rhino JavaScript 也会遍历不存在的元素:http://ideone.com/7Z3AFh(与 for..in 不同).

I just found that Rhino JavaScript traverses non-existent elements also: http://ideone.com/7Z3AFh (unlike for..in).

推荐答案

ECMA-262,第 5 版 规范和 MDN 的 Array.forEach() 页面 都显示了 .forEach() 的算法,它肯定会按索引升序迭代数组元素(跳过从未赋值的索引).

The ECMA-262, 5th edition specification and MDN's Array.forEach() page both show the algorithm for .forEach(), and it will definitely iterate over array elements in ascending index order (skipping indices that were never assigned a value).

当然,有些浏览器可能没有正确实现该算法,但我不知道有哪些没有.

Of course, some browsers may not implement that algorithm properly, but I'm not aware of any that don't.

这篇关于JavaScript array.forEach 是否按升序遍历元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆