1.forEach,map,filter三个函数者是相同的调用参数。(callback[, thisArg])

callback is invoked with three arguments:

  • the element value
  • the element index
  • the array being traversed
if (!Array.prototype.forEach) {
    Array.prototype.forEach = function (fn, thisObj) {
        var scope = thisObj || window;
        for (var i = 0, j = this.length; i < j; ++i) {
            fn.call(scope, this[i], i, this);
        }
    };
}

if (!Array.prototype.map) {
    Array.prototype.map = function (fn, thisObj) {
        var scope = thisObj || window;

        var res = [];//区别在于这里,forEach不会生成新的数组

        for (var i = 0, j = this.length; i < j; ++i) {
         res[i] = fn.call(scope, this[i], i, this);
        }
    return res;
    };
}

if (!Array.prototype.filter) {
    Array.prototype.filter = function (fn, thisObj) {
        var scope = thisObj || window;
        var a = [];
        for (var i = 0, j = this.length; i < j; ++i) {
            if (!fn.call(scope, this[i], i, this)) {
                continue;
            }
            a.push(this[i]);
        }
        return a;
    };
}

2.示例

function logArrayElements(element, index, array) {
    console.log("a[" + index + "] = " + element);
}
[2, 5, 9].forEach(logArrayElements);
// a[0] = 2
// a[1] = 5
// a[2] = 9
var map = Array.prototype.map
var a = map.call("Hello World", function(x) { return x.charCodeAt(0); })
// a now equals [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]

var numbers = [1, 4, 9];
var roots = numbers.map(Math.sqrt);
/* roots is now [1, 2, 3], numbers is still [1, 4, 9] */
function isBigEnough(element, index, array) {
  return (element >= 10);
}
var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
// filtered is [12, 130, 44]

 

相关文章:

  • 2021-11-20
  • 2021-10-23
  • 2021-10-03
  • 2022-02-07
  • 2023-03-09
  • 2021-12-30
  • 2022-01-02
猜你喜欢
  • 2021-07-11
  • 2022-03-02
  • 2022-12-23
  • 2021-08-12
  • 2021-09-16
  • 2022-01-02
  • 2021-10-22
相关资源
相似解决方案