JavaScript array.forEach 是否按升序遍历元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13600922/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 12:27:06  来源:igfitidea点击:

Does JavaScript array.forEach traverse elements in ascending order

javascriptarrayssortingforeach

提问by Rodion Gorkovenko

In JavaScript I can have an array with holes:

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

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.

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

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).

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

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

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

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

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

回答by nnnnnn

The ECMA-262, 5th editionspecification and MDN's Array.forEach()pageboth 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).

ECMA-262,第5版规范和MDN的Array.forEach()页面都显示了算法.forEach(),它肯定会叠代升序索引顺序数组元素(跳过指数未曾被分配一个值)。

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

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

回答by T.J. Crowder

The specification saysforEachwill visit the array elements in numeric order. It doesn't visit elements that don't exist. See the link for details. So for your example array, it will visit element 0, then 3, then 5. The order in which you add them to the array has no effect on the order in which they're visited.

规范说forEach将按数字顺序访问数组元素。它不会访问不存在的元素。有关详细信息,请参阅链接。因此,对于您的示例数组,它将访问 element 0, then 3, then 5。您将它们添加到数组中的顺序对它们被访问的顺序没有影响。

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).

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

The order in which for-invisits object properties is notdefined by the specification, not even in ES2015 (aka ES6), despite the fact that ES2015 defines an order for object properties — that order doesn't apply to for-inor Object.keys. (More about that in this answer.) If you want to visit properties in the order defined in ES2015, you can use Object.getOwnPropertyNames(for properties that aren't defined with Symbolnames) or Reflect.ownKeys(for both Symboland string property names [remember numeric property names are really strings]). Both of those dorespect property order.

在该命令for-in访问对象属性是通过本说明书中,尽管ES2015的事实定义的,甚至没有在ES2015(又名ES6)定义了对象属性的顺序 的顺序并不适用于-for-inObject.keys。(更多关于这个答案。)如果你想按照 ES2015 中定义的顺序访问属性,你可以使用Object.getOwnPropertyNames(对于没有定义Symbol名称的属性)或Reflect.ownKeys(对于Symbol字符串属性名称[记住数字属性名称是真正的字符串])。两者尊重财产秩序。

回答by Bruno

Straight out of the ECMAScript standard

直接脱离ECMAScript 标准

forEachcalls callbackfn once for each element present in the array, in ascending order. callbackfn is called only for elements of the array which actually exist; it is not called for missing elements of the array.

forEach为数组中的每个元素按升序调用 callbackfn 一次。callbackfn 仅针对实际存在的数组元素调用;不需要数组的缺失元素。

So Array.forEach will skip certain elements in an array. Your example

所以 Array.forEach 将跳过数组中的某些元素。你的榜样

a.forEach( function( value ) { console.log( value ) }); // prints 100, 300, 200

If you do want to traverse the array in ascending order and all your elements are numbers then you can sort the array beforehand like so

如果您确实想按升序遍历数组并且所有元素都是数字,那么您可以像这样预先对数组进行排序

a.sort( function( a, b ) { return a - b });
// this now prints 100, 200, 300
a.forEach( function( value ) { console.log( value ) });