zoukankan      html  css  js  c++  java
  • 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]
  • 相关阅读:
    nginx配置
    线程与进程的区别:
    java面试题1
    递归的定义和优缺点
    使用jedis连接redis可能会出现的问题及解决方案
    Linux上安装Redis
    Linux 权限管理
    Maven
    网址备份
    反射
  • 原文地址:https://www.cnblogs.com/yuyutianxia/p/3271798.html
Copyright © 2011-2022 走看看