Does “for…of” loop iteration follow the array order in JavaScript?

前端 未结 3 1351
Happy的楠姐
Happy的楠姐 2020-12-08 20:02

Iterating over an array using for...in doesn\'t guarantee order, however ES6 introduces a new construct for...of.

My limited testing of im

3条回答
  •  情歌与酒
    2020-12-08 20:25

    My limited testing of implementations of for...of indicate it does iterate in order on array, but is this property guaranteed?

    Yes. But hunting it down is a littlebit complicated, as for of doesn't only iterate arrays (like for in does enumerate objects). Instead, it generically iterates all iterable objects - in the order that their respective iterator supplies.

    In fact arrays are such an iterable, and when getting an iterator from them it will be an iterator that yields all elements of the array in the same order as they can be found in the array. You can read the spec for ArrayIterator objects, they basically work like a for (var index=0; index loop.

提交回复
热议问题