gpt4 book ai didi

javascript - foreach 是否保证每次在同一数据集上以相同的顺序循环?

转载 作者:行者123 更新时间:2023-12-01 01:28:19 25 4
gpt4 key购买 nike

foreach (Array.prototype.forEach) 是否保证每次在相同的数据集上以相同的顺序循环?为什么?

最佳答案

如果实现遵循标准,那么是的,forEach按顺序处理数组,但忽略未初始化值的稀疏数组除外。 forEach() the spec 中描述:

forEach calls 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.

它循环遍历索引,开头为:

Let lenValue be the result of calling the [[Get]] internal method of O with the argument "length" Let k be 0.
Repeat, while k < len
...
Increase k by 1

在 javascript 中,数组对象并具有 length作为索引的属性和整数键。该规范表示它将从 k=0 开始。并调用arr[k]按升序排列k < length 。它将为 arr 的所有值调用回调。有特性k

稀疏数组的示例,其中 forEach忽略元素可能如下所示:

let a  = Array(10)
a[5] = "Five"
a[9] = "Nine"
console.log(a)
// ignores initialized values:
a.forEach((item) => console.log(item))

如果您在回调中执行异步操作,则回调可能不会按顺序发生,但实际上仍然如此。

根据评论进行编辑:

您可以通过一些技巧将对象传递给 forEach看起来像一个数组(它有长度和整数键)。 forEach将按 index 顺序调用项目,而不是它们在对象上定义的顺序。例如:

// an object that has enough info
// for forEach to use
let o = {
3: "three",
2: "two",
0: "zero",
1: "one",

length: 4
}

// calls in order of indexes, not order keys were defined
Array.prototype.forEach.call( o, (i) => console.log(i))

关于javascript - foreach 是否保证每次在同一数据集上以相同的顺序循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53546553/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com