Array.map()迭代舊陣列元素產生新陣列

Javascript的Array.map()方法:

     Array.map()方法的參數是一個回呼函式,利用此回呼函式,Array.map()方法可以用來對陣列中的元素進行操作。除了被刪除的元素或是未給訂初始值的元素除外,map()方法會為每個元素呼叫一次回呼函式,並傳回一個值,這些值會被丟進一個新的陣列,再藉由map方法將該陣列傳回。

     map()方法定義在ECMA-262第五版中,可能會有些瀏覽器不支援此方法。若要確定在所有瀏覽器中都能正確的執行,可以在原型中自行定義此方法。

Array.map()的語法:

array.map( callbackfn [ , thisArg ] )

callbackfn:回呼函式,map()方法利用此函式來來操作陣列中的元素。

                     callbackfn有三個傳入值element、index、array,

                     element:元素的值。

                     index:元素索引,可省略。

                     array:測試的陣列,可省略。

                     傳回值:回呼函式會有一傳回值,並由map()方法組合成陣列後,由map()傳回。

thisArg:callbackfn中的this代表的物件,如果省略則callbackfn中的this代表全域物件。

Array.map()的範例:

<script type="text/javascript">
function double(element, index, array) {
  return element*2;
}
var myArray = [1,2,3,4,5,6,7,8,9,10];
document.writeln("原陣列:"+myArray );
document.writeln("<br/>");
document.writeln("After Array.map():"+myArray.map(double) );
</script>

Array.map()的範例輸出:

原陣列:1,2,3,4,5,6,7,8,9,10 
After Array.map():2,4,6,8,10,12,14,16,18,20

在原型中新增Array.map()方法:

     Array.map()方法是ECMS-262中的標準方法,但並非所有瀏覽器都支援,為確保在所有瀏覽器中都能正確執行,可自行在原型中定義該方法。下面是來自MDN中Array.prototype.map()的程式,將其放入<script>的開頭:

// Production steps of ECMA-262, Edition 5, 15.4.4.19
// Reference: 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. Let O be the result of calling ToObject passing the |this| value as the argument.
    var O = Object(this);
    // 2. Let lenValue be the result of calling the Get internal method of O with the argument "length".
    // 3. Let len be ToUint32(lenValue).
    var len = O.length >>> 0;
    // 4. If IsCallable(callback) is false, throw a TypeError exception.
    // See: http://es5.github.com/#x9.11
    if (typeof callback !== "function") {
      throw new TypeError(callback + " is not a function");
    }
    // 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
    if (thisArg) {
      T = thisArg;
    }
    // 6. Let A be a new array created as if by the expression new Array(len) where Array is
    // the standard built-in constructor with that name and len is the value of len.
    A = new Array(len);
    // 7. Let k be 0
    k = 0;
    // 8. Repeat, while k < len
    while(k < len) {
      var kValue, mappedValue;
      // a. Let Pk be ToString(k).
      //   This is implicit for LHS operands of the in operator
      // b. Let kPresent be the result of calling the HasProperty internal method of O with argument Pk.
      //   This step can be combined with c
      // c. If kPresent is true, then
      if (k in O) {
 
        // i. Let kValue be the result of calling the Get internal method of O with argument Pk.
        kValue = O[ k ];
        // ii. Let mappedValue be the result of calling the Call internal method of callback
        // with T as the this value and argument list containing kValue, k, and O.
        mappedValue = callback.call(T, kValue, k, O);
        // iii. Call the DefineOwnProperty internal method of A with arguments
        // Pk, Property Descriptor {Value: mappedValue, : true, Enumerable: true, Configurable: true},
        // and false.
        // In browsers that support Object.defineProperty, use the following:
        // Object.defineProperty(A, Pk, { value: mappedValue, writable: true, enumerable: true, configurable: true });
        // For best browser support, use the following:
        A[ k ] = mappedValue;
      }
      // d. Increase k by 1.
      k++;
    }
 
    // 9. return A
    return A;
  };     
}
 
關於Array物件的其他屬性與方法,請參考:陣列物件 Array
 
 

  按個讚!~支持本站!~

FB推薦載入中