javaScript高级教程(一)javaScript 1.6 Array 新增函数

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]
原文地址:https://www.cnblogs.com/yuyutianxia/p/3271798.html