對映值

通常需要根據現有陣列的值生成新陣列。

例如,要從字串陣列生成字串長度陣列:

Version >= 5.1

['one', 'two', 'three', 'four'].map(function(value, index, arr) {
  return value.length;
});
// → [3, 3, 5, 4]

Version >= 6

['one', 'two', 'three', 'four'].map(value => value.length);
// → [3, 3, 5, 4]

在此示例中,為 map() 函式提供了一個匿名函式,map 函式將為陣列中的每個元素呼叫它,按以下順序提供以下引數:

  • 元素本身
  • 元素的索引(0,1 …)
  • 整個陣列

另外,map() 提供可選的第二個引數,以便在對映函式中設定 this 的值。根據執行環境,this 的預設值可能會有所不同:

在瀏覽器中,this 的預設值始終為 window

['one', 'two'].map(function(value, index, arr) {
  console.log(this); // window (the default value in browsers)
  return value.length;
});

你可以將其更改為任何自定義物件,如下所示:

['one', 'two'].map(function(value, index, arr) {
  console.log(this); // Object { documentation: "randomObject" }
  return value.length;
}, {
  documentation: 'randomObject'
});