原生JS forEach和map遍历的区别以及兼容写法

2025-05-09 00:03:20
推荐回答(1个)
回答1:

forEach 没有返回值,map 有返回值。

if ( !Array.prototype.forEach ) {
Array.prototype.forEach = function forEach( callback, thisArg ) {
var T, k;
if ( this == null ) {
throw new TypeError( "this is null or not defined" );
}
var O = Object(this);
var len = O.length >>> 0; 
if ( typeof callback !== "function" ) {
throw new TypeError( callback + " is not a function" );
}
if ( arguments.length > 1 ) {
T = thisArg;
}
k = 0;
while( k < len ) {
var kValue;
if ( k in O ) {
kValue = O[ k ];
callback.call( T, kValue, k, O );
}
k++;
}
};
}
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");
        }

        var O = Object(this);
        var len = O.length >>> 0;

        if (typeof callback !== "function") {
            throw new TypeError(callback + " is not a function");
        }

        if (thisArg) {
            T = thisArg;
        }

        A = new Array(len);

        k = 0;
        while(k < len) {

            var kValue, mappedValue;
            if (k in O) {
                kValue = O[ k ];
                mappedValue = callback.call(T, kValue, k, O);
                A[ k ] = mappedValue;
            }
            k++;
        }
        return A;
    };
}