Javascript中Array.prototype.map()詳解,array.prototype

來源:互聯網
上載者:User

Javascript中Array.prototype.map()詳解,array.prototype

在我們日常開發中,操作和轉換數組是一件很常見的操作,下面我們來看一個執行個體:

複製代碼 代碼如下:
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);

從上例可以看出,所有的操作重複率都比較高,如何來最佳化呢,幸運的是Ecmascript 5給我們提供了一個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替換掉了for迴圈部分,從而只需要關心每個元素自身的實現邏輯。關於map方法詳情請戳這裡。

1.map基本定義:
array.map(callback[, thisArg]);

map 方法會給原數組中的每個元素都按順序調用一次 callback 函數。callback 每次執行後的傳回值組合起來形成一個新數組。 callback 函數只會在有值的索引上被調用;那些從來沒被賦過值或者使用 delete 刪除的索引則不會被調用。

callback 函數會被自動傳入三個參數:數組元素,元素索引,原數組本身。

如果 thisArg 參數有值,則每次 callback 函數被調用的時候,this 都會指向 thisArg 參數上的這個對象。如果省略了 thisArg 參數,或者賦值為 null 或 undefined,則 this 指向全域對象 。

map 不修改調用它的原數組本身(當然可以在 callback 執行時改變原數組)。

當一個數組運行 map 方法時,數組的長度在調用第一次 callback 方法之前就已經確定。在 map 方法整個運行過程中,不管 callback 函數中的操作給原數組是添加還是刪除了元素。map 方法都不會知道,如果數組元素增加,則新增加的元素不會被 map 遍曆到,如果數組元素減少,則 map 方法還會認為原數組的長度沒變,從而導致數組訪問越界。如果數組中的元素被改變或刪除,則他們被傳入 callback 的值是 map 方法遍曆到他們那一刻時的值。

2.map執行個體:

複製代碼 代碼如下:
//執行個體一:字串上調用map方法
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);

上例示範了在一個String上使用map方法擷取字串中每個字元所對應的 ASCII 碼組成的數組。請注意看列印的console.log(arr)列印的結果。

複製代碼 代碼如下:
//執行個體二:下面的操作結果是什嗎?
var result = ["1", "2", "3"].map(parseInt);
//Outputs: [1, NaN, NaN]
console.log(result);

也許你會有疑問,為什麼不是[1,2,3]呢?我們知道parseInt方法可接收兩個參數,第一個參數為需要轉換的值,第二個參數為進位數,不瞭解的可以戳這裡。當我們使用map方法的時候,callback函數接收三個參數,而parseInt最多隻能接收兩個參數,以至於第三個參數被直接捨棄,與此同時,parseInt把傳過來的索引值當成進位數來使用.從而返回了NaN。看下面的輸出結果:

複製代碼 代碼如下:
//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呢?為瞭解釋這個問題,我們看看官方的描述:
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).
在第三點中當string為其他值時,進位預設為10。

那麼我們如何修改才能使上例正常輸出呢?看下例:

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

3.map方法的相容性:
map方法在IE8及以下瀏覽器不支援,要想相容老版本的瀏覽器,可以:

a) Don't use map.b) Use something like es5-shim to make older IE's support map.c) Use the _.map method in Underscore or Lodash for an equivalent utility function.

以上就是對map方法的理解,希望對初學者有所協助,文中不妥之處,還望斧正!


javascript中通過 prototype定義的屬性 在方法中怎訪問

<script type="text/javascript"> // 定義一個 Fun 類, public class Fun {} function Fun() { // 這裡定義一個方法,調用 Fun 類中的 name 屬性,必須使用 this.name 代表該對象.name屬性 this.say = function() { alert("你好,我是" + this.name); } } // 為 Fun 綁定屬性和方法 Fun.prototype = { // 綁定 name 屬性, var name = "zhong"; name: "zhong" }; window.onload = function() { // 必須使用 new Fun();執行個體化 Fun 類,alert 出他的 name 值 alert(new Fun().name); // 必須使用 new Fun();執行個體化 Fun 類,調用 say() 方法 new Fun().say(); }</script>
 
javascript中array對象的index屬性是什

應該是內元素的下標吧。例如:a(), a[0],a[1],a[2],a[3],... , 0,1,2, 3就index.
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.