• 数组方法-reduce 和 ES6扩展运算符


    1.reduce方法介绍

    应用场景1:计算数组中所有值总和

    var numbers = [1, 2, 3];
    var sumVal = numbers.reduce(function(sum, number) {
      return sum + number;
      //0是sum的初始化值
    }, 0);
    console.log(sumVal);
    

    应用场景2:将对象数组中对象的某个属性抽离到另外一个数组中

    var colors = [
      { color: "red" }, 
      { color: "green" }, 
      { color: "black" }
    ];
    var colorsNew = colors.reduce(function(colorArr, colors) {
      colorArr.push(colors.color);
      return colorArr;
    }, []);
    console.log(colorsNew);
    //结果:["red", "green", "black"]
    

    应用场景3:判断字符串中括号是否对称

    function balanceParents(string) {
      return !string.split("").reduce(function(previous, char) {
        if (char == "(") {
          return ++previous;
        }
        if (char == ")") {
          return --previous;
        }
        return previous;
      }, 0);
    }
    console.log(balanceParents("(())aaadsd))"));//结果:false

    2.扩展运算符详细介绍

    应用场景1:将单独的数值组成数组返回

    //使用"..."(扩展运算符)自动将传入的参数组成数组:numbers
    function addNumber(...numbers) {
      return numbers.reduce((sum, item) => {
        return sum + item;
      }, 0);
    }
    console.log(addNumber(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
    //结果:55
    

    应用场景2:组合多个数组 

    var defaultNum = [1, 2, 3, 4, 5];
    var myNum = [10, 20];
    var yourNum = [9, 8, 7];
    console.log([11, 22, 33, ...defaultNum, ...myNum, ...yourNum]);
    //结果: [11, 22, 33, 1, 2, 3, 4, 5, 10, 20, 9, 8, 7]
    
  • 相关阅读:
    实验四 决策树算法及应用
    实验三 朴素贝叶斯算法及应用
    实验二 K-近邻算法及应用
    实验一 感知器及其应用
    实验三 面向对象分析与设计
    实验二 结构化分析与设计
    实验一 软件开发文档与工具的安装与使用
    ATM管理系统
    活动图与流程图的区别与联系
    四则运算题目生成程序
  • 原文地址:https://www.cnblogs.com/yxkNotes/p/11550262.html
Copyright © 2020-2023  润新知