前幾天去別的公司面試遇到個這樣的問題,相容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;
        }
    }
})()