簡體   English   中英

javascript數組方法(map,forEach,reduce等)的迭代順序是否確定?

[英]Is the order of iteration for javascript array methods (map, forEach, reduce, etc) deterministic?

使用本機方法(map,forEach,reduce,filter等)之一遍歷數組的順序是否由標准確定並保證?

EG,foo,bar,baz和qux是否保證為[0, 2, 6, 12] 0,2,6,12 [0, 2, 6, 12]

const a = [1, 2, 3, 4];
const foo = a.map((item, index) => item * index);
const bar = []; a.forEach((item, index) => bar[index] = item * index);
const baz = []; a.reduce((total, item, index) => baz[index] = item * index, 0);
const qux = []; a.filter((item, index) => qux[index] = item * index);
// etc

(這些是(非常)人為的示例)

通常,它們的行為與for循環完全相同:

 for(var i = 0; i < this.length; i++)

只有一個例外, reduceRight像這樣迭代:

 for(var i = this.length - 1; i+1 ; i-- )

與上面的示例不同,它們跳過了未定義的屬性。

對於數組中存在的每個元素,按升序調用回調函數。 要求缺少元素。 (缺少元素?是的,JavaScript處理稀疏數組)

var test = [];
test[30] = 'Test'; // sparse array, only one element defined.

test.forEach(
  function(value){
    console.log(value); // will only be called one time.
  }
);

來自標准: ECMA-262

22.1.3.10 Array.prototype.forEach(callbackfn [,thisArg])

注1

callbackfn應該是一個接受三個參數的函數。 forEach對數組中存在的每個元素按升序調用一次callbackfn 僅對實際存在的數組元素調用callbackfn 它不要求缺少數組元素

如果提供了thisArg參數,則它將用作每次調用callbackfnthis值。 如果未提供,則使用undefined

使用三個參數調用callbackfn :元素的值,元素的索引和要遍歷的對象。

forEach不會直接改變在其上調用它的對象,但是可以通過對callbackfn的調用來改變該對象。

使用一個或兩個參數調用forEach方法時,將執行以下步驟:

  1. 讓O成為? ToObject(此值)。
  2. 讓倫成為? ToLength(?Get(O,“ length”))。
  3. 如果IsCallable(callbackfn)為false ,則拋出TypeError異常。
  4. 如果提供了thisArg,則讓T為thisArg; 否則讓T 不確定
  5. 令k為0。
  6. 重復,而k <len a。 讓Pk成為! ToString(k)。 b。 讓kPresent為? HasProperty(O,Pk)。 C。 如果kPresent為true ,那么我。 令kValue為? 獲取(O,Pk)。 ii。 執行? Call(callbackfn,T,«kValue,k,O»)。 d。 將k增加1。
  7. 返回undefined

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM