美文网首页
迭代大法好

迭代大法好

作者: 我是白夜 | 来源:发表于2016-11-29 10:44 被阅读0次

    本文主要整理了Array.prototype方法的使用,参考于ECMAScript 5;

    1. Array.prototype.indexOf (js v1.6)

    2. Array.prototype.lastIndexOf (js v1.6)

    3. Array.prototype.every (js v1.6)

    4. Array.prototype.some (js v1.6)

    5. Array.prototype.forEach (js v1.6)

    6. Array.prototype.map (js v1.6)

    7. Array.prototype.filter (js v1.6)

    8. Array.prototype.isArray (js v1.6)

    9. Array.prototype.reduce(js v1.8)

    10. Array.prototype.reduceRight(js v1.8)

    浏览器支持:

    • Opera 11+
    • Firefox 3.6+
    • Safari 5+
    • Chrome 8+
    • Internet Explorer 9+

    indexOf()

    indexOf()方法返回在该数组中第一个找到的元素位置,如果它不存在则返回-1。

    使用for:

    var arr = ['apple','orange','pear'],
        found = false;
    for(var i= 0, l = arr.length; i< l; i++){
        if(arr[i] === 'orange'){
            found = true;
        }
    }
    console.log("found:",found);//true
    

    使用indexOf():

    var arr = ['apple', 'orange', 'pear'];
    console.log("found:", arr.indexOf("orange") != -1); //true
    

    兼容性处理:

    // 对于古董浏览器,如IE6-IE8
    if (typeof Array.prototype.forEach != "function") {
      Array.prototype.forEach = function (fn, context) {
        for (var k = 0, length = this.length; k < length; k++) {
          if (typeof fn === "function" && Object.prototype.hasOwnProperty.call(this, k)) {
            fn.call(context, this[k], k, this);
          }
        }
      };
    }
    

    lastindexOf()

    lastIndexOf() 方法返回在该数组中最后一个找到的元素位置,和 indexof相反。

    使用lastIndexOf():

    var data = [2, 5, 7, 3, 5];
    
    console.log(data.lastIndexOf(5)); // 4
    console.log(data.lastIndexOf(5, 3)); // 1 (从后往前,索引值小于3的开始搜索)
    
    console.log(data.lastIndexOf(4)); // -1 (未找到)
    

    兼容性处理:

    if (typeof Array.prototype.lastIndexOf != "function") {
      Array.prototype.lastIndexOf = function (searchElement, fromIndex) {
        var index = -1, length = this.length;
        fromIndex = fromIndex * 1 || length - 1;
    
        for (var k = length - 1; k > -1; k-=1) {
            if (k <= fromIndex && this[k] === searchElement) {
                index = k;
                break;
            }
        }
        return index;
      };
    }
    

    every()

    evety()方法可是检测数组中的每一项是否符合条件

    使用for:

    /* 
    * 是否全部大于0
    */
    var ary = [12,23,24,42,1];
    var result = function(){
      for (var i = 0; i < ary.length; i++) {
        if(ary[i] < 0){
           return false;
        }
      }
      return true; //需全部满足
    }
    console.log(result()) //全部满足,返回true
    

    使用every:

    var ary = [12,23,24,42,1];
    var result = ary.every(function(item, index){
      return item > 0
    })
    console.log(result)
    

    兼容性处理:

    if (typeof Array.prototype.every != "function") {
      Array.prototype.every = function (fn, context) {
        var passed = true;
        if (typeof fn === "function") {
           for (var k = 0, length = this.length; k < length; k++) {
              if (passed === false) break;
              passed = !!fn.call(context, this[k], k, this);
          }
        }
        return passed;
      };
    }
    

    some()

    some()可以检测数组中是否有某一项符合条件

    使用for:

    /* 
    * 是否存在小于0的项
    */
    var ary = [12,23,-24,42,1];
    var result = function(){
      for (var i = 0; i < ary.length; i++) {
        if(ary[i] < 0){
           return true;
        }
      }
      return false; //只需满足一个
    }
    console.log(result())  //有一项小于0,返回true
    

    使用some:

    var ary = [12,23,-24,42,1];
    var result = ary.some(function(item, index){
      return item < 0
    })
    console.log(result)
    

    兼容性处理:

    if (typeof Array.prototype.some != "function") {
      Array.prototype.some = function (fn, context) {
        var passed = false;
        if (typeof fn === "function") {
          for (var k = 0, length = this.length; k < length; k++) {
              if (passed === true) break;
              passed = !!fn.call(context, this[k], k, this);
          }
        }
        return passed;
      };
    }
    

    foEach()

    forEach()为每个元素执行对应的方法

    使用for:

    var arr = [1,2,3,4,5,6,7,8];
    
    for(var i= 0, l = arr.length; i< l; i++){
        console.log(arr[i]);
    }
    

    使用forEach:

    var arr = [1,2,3,4,5,6,7,8];
    
    arr.forEach(function(item,index){
        console.log(item);
    }); 
    

    map()

    map()对数组的每个元素进行一定操作(映射)后,会返回一个新的数组map()是<u>处理服务器返回数据时是一个非常实用的函数。</u>

    使用for:

    var oldArr = [{first_name:"Colin",last_name:"Toh"},{first_name:"Addy",last_name:"Osmani"},{first_name:"Yehuda",last_name:"Katz"}];
    
    function getNewArr(){
      var newArr = [];
      for(var i= 0, l = oldArr.length; i< l; i++){
        var item = oldArr[i];
        item.full_name = [item.first_name,item.last_name].join(" ");
        newArr[i] = item;
      }
      return newArr;
    }
    console.log(getNewArr());
    

    使用map:

    var oldArr = [{first_name:"Colin",last_name:"Toh"},{first_name:"Addy",last_name:"Osmani"},{first_name:"Yehuda",last_name:"Katz"}];
    
    function getNewArr(){
      return oldArr.map(function(item,index){
        item.full_name = [item.first_name,item.last_name].join(" ");
        return item;
      });
    
    }
    console.log(getNewArr());
    

    兼容性处理:

    if (typeof Array.prototype.map != "function") {
      Array.prototype.map = function (fn, context) {
        var arr = [];
        if (typeof fn === "function") {
          for (var k = 0, length = this.length; k < length; k++) {      
             arr.push(fn.call(context, this[k], k, this));
          }
        }
        return arr;
      };
    }
    

    filter()

    filter() 筛选出数组中符合条件的项,并组成新数组。

    使用for:

    var arr = [
      {"name":"apple", "count": 2},
      {"name":"orange", "count": 5},
      {"name":"pear", "count": 3},
      {"name":"orange", "count": 16},
    ];
    var newArr = [];
    for(var i= 0, l = arr.length; i< l; i++){
      if(arr[i].name === "orange" ){
        newArr.push(arr[i]);
      }
    }
    console.log("Filter results:",newArr);
    

    使用filter():

    var arr = [
      {"name":"apple", "count": 2},
      {"name":"orange", "count": 5},
      {"name":"pear", "count": 3},
      {"name":"orange", "count": 16},
    ];
    var newArr = arr.filter(function(item){
      return item.name === "orange";
    });
    console.log("Filter results:",newArr);
    
    

    兼容性处理:

    if (typeof Array.prototype.filter != "function") {
      Array.prototype.filter = function (fn, context) {
        var arr = [];
        if (typeof fn === "function") {
           for (var k = 0, length = this.length; k < length; k++) {
              fn.call(context, this[k], k, this) && arr.push(this[k]);
           }
        }
        return arr;
      };
    }
    

    reduce()

    reduce()可以实现一个累加器的功能,让数组中的前项和后项做某种计算,并累计最终值。

    语法: array.reduce(callbackfn[, initialValue])

    参数 定义
    array 必需。一个数组对象
    callbackfn 必需。一个接受最多四个参数的函数。对于数组中的每个元素,reduce 方法都会调用 callbackfn 函数一次。
    initialValue 可选。如果指定 initialValue,则它将用作初始值来启动累积。第一次调用 callbackfn 函数会将此值作为参数而非数组值提供

    使用reduce计算和值

    var sum = [1, 2, 3, 4].reduce(function (previous, current, index, array) {
      return previous + current;
    });
    
    console.log(sum); // 10
    
    /* 
    1. 因为initialValue不存在,因此一开始的previous值等于数组的第一个元素。
    2. 从而current值在第一次调用的时候就是2.
    3. 最后两个参数为索引值index以及数组本身array.
    
    ---------------------------
    以下位迭代过程演示代码*/
    
    // 初始设置
    previous = initialValue = 1, current = 2
    
    // 第一次迭代
    previous = (1 + 2) =  3, current = 3
    
    // 第二次迭代
    previous = (3 + 3) =  6, current = 4
    
    // 第三次迭代
    previous = (6 + 4) =  10, current = undefined  //(退出)
    

    使用reduce实现二维数组扁平化:

    var matrix = [
      [1, 2],
      [3, 4],
      [5, 6]
    ];
    
    // 二维数组扁平化
    var flatten = matrix.reduce(function (previous, current) {
      return previous.concat(current);
    });
    
    console.log(flatten); // [1, 2, 3, 4, 5, 6]
    

    兼容性处理:

    if (typeof Array.prototype.reduce != "function") {
      Array.prototype.reduce = function (callback, initialValue ) {
         var previous = initialValue, k = 0, length = this.length;
         if (typeof initialValue === "undefined") {
            previous = this[0];
            k = 1;
         }
         
        if (typeof callback === "function") {
          for (k; k < length; k++) {
             this.hasOwnProperty(k) && (previous = callback(previous, this[k], k, this));
          }
        }
        return previous;
      };
    }
    

    reduceRight()

    reduce()方法的语法一样,但是是从末位arr.length-1开始计算

    语法: array.reduceRight(callbackfn[, initialValue])

    reduceRight计算递减

    var data = [1, 2, 3, 4];
    var specialDiff = data.reduceRight(function (previous, current, index) {
      if (index == 0) {
        return previous + current;
      }
      return previous - current;
    });
    
    console.log(specialDiff); // 0
    
    /*---------------------------
    以下位迭代过程演示代码*/
    
    // 初始设置
    index = 3, previous = initialValue = 4, current = 3
    
    // 第一次迭代
    index = 2, previous = (4- 3) = 1, current = 2
    
    // 第二次迭代
    index = 1, previous = (1 - 2) = -1, current = 1
    
    // 第三次迭代
    index = 0, previous = (-1 + 1) = 0, current = undefined (退出)
    
    

    兼容性处理:

    if (typeof Array.prototype.reduceRight != "function") {
      Array.prototype.reduceRight = function (callback, initialValue ) {
        var length = this.length, k = length - 1, previous = initialValue;
        if (typeof initialValue === "undefined") {
            previous = this[length - 1];
            k--;
        }
        if (typeof callback === "function") {
           for (k; k > -1; k-=1) {          
              this.hasOwnProperty(k) && (previous = callback(previous, this[k], k, this));
           }
        }
        return previous;
      };
    }
    

    迭代方法

    参考

    相关文章

      网友评论

          本文标题:迭代大法好

          本文链接:https://www.haomeiwen.com/subject/jtdfpttx.html