相容低版本JS的Array.map方法

來源:互聯網
上載者:User

標籤:傳回值   val   對象   value   div   row   key   nbsp   erro   

前幾天去別的公司面試遇到個這樣的問題,相容IE7下的Array.map方法,一臉蒙蔽。後面回來查了下資料發現。Array.map方法是ECMA-262 標準中新添加的方法,在低版本的JS中是木有的。

看如下相容性實現方式:

  實現思路:1,先驗證this對象,再將this用Object封裝成obj。

                    2,擷取封裝後的obj的屬性長度

                    3,驗證是否有回調方法

                    4,根據obj的屬性長度lengh產生新的數組,new Array(length)。

                    5,遍曆obj對象,擷取mapKey,mapValue,並將傳回值添加到新數組arr中。

                    6,將整個新的數組返回。

   代碼實現:

(function(){    if(!Array.prototype.map) {        Array.prototype.map = function(callback, args) {            var arg , arr, index ;             if(this == null) {                throw new TypeError(‘this is null or not defined‘);            }             var obj = new Object(this);            var len = obj >>> 0;  //擷取obj的長度             if(Object.prototype.toString.call(callback) != ‘[object Function]‘) {                throw new TypeError(callback + ‘is not a function‘);            }             if(args) {                arg = args;            }            // 建立新數組,長度為原數組O長度len            arr = new Array(len);            index = 0;             while(index < len) {                var kValue, mappedValue;                if(index in obj) {                    //kValue為索引k對應的值.                    kValue = obj[index];                    // 執行callback,this指向arr,參數有三個.分別是kValue:值,index:索引,obj:原數組.                    mappedValue = callback.call(arg, kValue, index, obj);                    // 傳回值添加到新數組arr中.                    arr[index] = mappedValue;                }                index ++;            }            return arr;        }    }})()

   

相容低版本JS的Array.map方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.