DIV CSS 佈局教程網

Array.prototype.map() 詳解:用轉換思維取代 for 迴圈
編輯:JavaScript基礎知識     

日常開發中,把一個陣列轉換成另一個陣列是非常典型的場景。先看一段傳統寫法:

var desColors = [],
    srcColors = [
        {r: 255, g: 255, b: 255 }, // White
        {r: 128, g: 128, b: 128 }, // Gray
        {r: 0,   g: 0,   b: 0   }  // Black
    ];

for (var i = 0, ilen = srcColors.length; i < ilen; i++) {
    var color = srcColors[i],
        format = function(color) {
            return Math.round(color / 2);
        };

    desColors.push( {
        r: format(color.r),
        g: format(color.g),
        b: format(color.b)
    });
}

// Outputs:
// [
//    {r: 128, g: 128, b: 128 },
//    {r: 64,  g: 64,  b: 64  },
//    {r: 0,   g: 0,   b: 0   }
// ];
console.log(desColors);

這段程式碼沒問題,但迴圈控制、索引管理、push 操作混在一起,真正想表達的「每個顏色都除以二」反而被淹沒了。ES5 提供的 map 方法可以讓意圖清楚很多:

var srcColors = [
        {r: 255, g: 255, b: 255 }, // White
        {r: 128, g: 128, b: 128 }, // Gray
        {r: 0,   g: 0,   b: 0   }  // Black
    ],
    desColors = srcColors.map(function(val) {
      var format = function(color) {
            return Math.round(color/2);
      };
      return {
            r: format(val.r),
            g: format(val.g),
            b: format(val.b)
      }
    });

// Outputs:
// [
//    {r: 128, g: 128, b: 128 },
//    {r: 64,  g: 64,  b: 64  },
//    {r: 0,   g: 0,   b: 0   }
// ];
console.log(desColors);

改用 map 之後,我們只需要關心「單一元素怎麼轉換」,其餘交給語言本身處理。

基本定義

array.map(callback[, thisArg]);

map 會依序對原陣列的每個元素呼叫一次 callback,並把每次的回傳值收集成一個新陣列。幾個重要特性:

  • callback 只會在有值的索引上被呼叫;從未賦值或用 delete 刪除的索引會被跳過。
  • callback 會收到三個參數:元素本身、元素索引、原陣列。
  • 若提供了 thisArg,callback 內的 this 就指向該物件;若省略或傳入 null/undefined,this 指向全域物件。
  • map 不會修改原陣列(但 callback 內部當然可以自行改動)。
  • 陣列長度在第一次呼叫 callback 之前就已確定。執行過程中 callback 若增刪元素,map 不會察覺:新增的元素不會被走訪,刪除的元素則可能造成索引錯位甚至取值越界。若元素被替換,傳給 callback 的是走訪到那一刻的值。

實用範例

例一:在字串上使用 map。透過 call 借用方法,可以取得每個字元對應的 ASCII 碼:

var result = Array.prototype.map.call("Hello world", function(x, index, arr) {
  // String {0: "H", 1: "e", 2: "l", 3: "l", 4: "o", 5: " ", 6: "w", 7: "o", 8: "r", 9: "l", 10: "d", length: 11}
  console.log(arr);
  return x.charCodeAt(0);
});
// Outputs: [72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]
console.log(result);

注意印出的 arr 其實是一個 String 物件,具備 length 與索引屬性,因此可以像陣列一樣被走訪。

例二:一個經典的面試陷阱。

var result = ["1", "2", "3"].map(parseInt);
// Outputs: [1, NaN, NaN]
console.log(result);

為什麼不是 [1, 2, 3]?因為 parseInt 接受兩個參數(字串與進位),而 map 傳入的是三個參數(元素、索引、原陣列)。第三個參數被忽略,但索引被當成進位使用了:

// Ouputs: 1
console.log(parseInt("1", 0));
// Ouputs: 1
console.log(parseInt("1", undefined));
// Ouputs: NaN
console.log(parseInt("2", 1));
// Ouputs: NaN
console.log(parseInt("3", 2));

後兩個顯然不合理(進位 1 與 2 都不是合法用法),前兩個則是因為官方定義了這樣的規則:

If radix is undefined or 0 (or absent), JavaScript assumes the following:
a) If the input string begins with “0x” or “0X”, radix is 16 (hexadecimal) and the remainder of the string is parsed.
b) If the input string begins with “0”, radix is eight (octal) or 10 (decimal). Exactly which radix is chosen is implementation-dependent. ECMAScript 5 specifies that 10 (decimal) is used, but not all browsers support this yet. For this reason always specify a radix when using parseInt.
c) If the input string begins with any other value, the radix is 10 (decimal).

正確的寫法是明確指定進位:

var result = ["1", "2", "3"].map(function(val) {
  return parseInt(val, 10);
});
// Outputs: [1, 2, 3]
console.log(result);

這也提醒我們:直接把內建函數當成 map 的回呼傳入,務必先確認它的簽名。

相容性

map 在 IE8 及以下版本不支援。若要兼顧舊版瀏覽器,可以:

a) 不使用 map;
b) 引入 es5-shim 這類 polyfill;
c) 使用 Underscore 或 Lodash 的 _.map。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved