js 數組map用法 Array.prototype.map()


map
這里的map不是“地圖”的意思,而是指“映射”。[].map(); 基本用法跟forEach方法類似:

array.map(callback,[ thisObject]);

callback的參數也類似:

[].map(function(value, index, array) {
    // ...
});

map方法的作用不難理解,“映射”嘛,也就是原數組被“映射”成對應新數組。下面這個例子是數值項求平方:

var data = [1, 2, 3, 4];

var arrayOfSquares = data.map(function (item) {
  return item * item;
});

alert(arrayOfSquares); // 1, 4, 9, 16

callback需要有return值,如果沒有,就像下面這樣:

var data = [1, 2, 3, 4];
var arrayOfSquares = data.map(function() {});

arrayOfSquares.forEach(console.log);

結果如下圖,可以看到,數組所有項都被映射成了undefined:
全部項都成了undefined

在實際使用的時候,我們可以利用map方法方便獲得對象數組中的特定屬性值們。例如下面這個例子(之后的兼容demo也是該例子):

var users = [
  {name: "張含韻", "email": "zhang@email.com"},
  {name: "江一燕",   "email": "jiang@email.com"},
  {name: "李小璐",  "email": "li@email.com"}
];

var emails = users.map(function (user) { return user.email; });

console.log(emails.join(", ")); // zhang@email.com, jiang@email.com, li@email.com

Array.prototype擴展可以讓IE6-IE8瀏覽器也支持map方法:

if (typeof Array.prototype.map != "function") {
  Array.prototype.map = function (fn, context) {
    var arr = [];
    if (typeof fn === "function") {
      for (var k = 0, length = this.length; k < length; k++) {      
         arr.push(fn.call(context, this[k], k, this));
      }
    }
    return arr;
  };
}

附官方Polyfill方法:

// 實現 ECMA-262, Edition 5, 15.4.4.19
// 參考: http://es5.github.com/#x15.4.4.19
if (!Array.prototype.map) {
  Array.prototype.map = function(callback, thisArg) {

    var T, A, k;

    if (this == null) {
      throw new TypeError(" this is null or not defined");
    }

    // 1. 將O賦值為調用map方法的數組.
    var O = Object(this);

    // 2.將len賦值為數組O的長度.
    var len = O.length >>> 0;

    // 3.如果callback不是函數,則拋出TypeError異常.
    if (Object.prototype.toString.call(callback) != "[object Function]") {
      throw new TypeError(callback + " is not a function");
    }

    // 4. 如果參數thisArg有值,則將T賦值為thisArg;否則T為undefined.
    if (thisArg) {
      T = thisArg;
    }

    // 5. 創建新數組A,長度為原數組O長度len
    A = new Array(len);

    // 6. 將k賦值為0
    k = 0;

    // 7. 當 k < len 時,執行循環.
    while(k < len) {

      var kValue, mappedValue;

      //遍歷O,k為原數組索引
      if (k in O) {

        //kValue為索引k對應的值.
        kValue = O[ k ];

        // 執行callback,this指向T,參數有三個.分別是kValue:值,k:索引,O:原數組.
        mappedValue = callback.call(T, kValue, k, O);

        // 返回值添加到新數組A中.
        A[ k ] = mappedValue;
      }
      // k自增1
      k++;
    }

    // 8. 返回新數組A
    return A;
  };      
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM