zoukankan      html  css  js  c++  java
  • 数组方法

    let arr = [1,2,4,5,6];
    let newArr = [];
    //es6 新增数组方法
    //forEach(); 遍历数组每一项,让每一项做某件事(执行callback函数);不能使用return
    //forEach 参数: callback this对象(执行 callback 函数时使用的this 值。)
    //callback参数:item index arr
    arr.forEach((item,index,arr) => {
    if(item%2 === 0){
    arr[index] = 0
    }
    });
    //map(); 方法创建一个新数组,其结果是该数组中的每个元素都调用一个提供的函数后返回的结果。
    //map 参数: callback this对象(执行 callback 函数时使用的this 值。)
    //callback 参数: item index arr
    newArr = arr.map((item,index,arr)=>{
    return item*2
    });
    //filter 筛选出数组中符合条件的项,组成新数组
    //filter 参数: callback this对象(执行 callback 函数时使用的this 值。)
    //callback 参数: item index arr
    newArr = arr.filter(function (item,index,arr) {
    return item%2 === 0
    });
    //reduce 让数组中的前项和后项做某种运算,并累计最终值
    //reduce 参数:callback initialValue(作为第一次调用 callback函数时的第一个参数的值。 如果没有提供初始值,则将使用数组中的第一个元素。)
    //callback 参数:accumulator currentValue currentIndex sourceArray
    let result = arr.reduce(function (pre,cur,index) {
    if(pre<3){
    return pre + cur;
    }
    else{
    return pre - cur;
    }
    },2);
    //every 检测数组中每一项是否符合条件 所有项满足返回true 否则返回false
    //every 参数:callback this对象(执行 callback 时使用的 this 值。)
    //callback 参数:item index arr
    let everyResult = arr.every(function (item,index) {
    return item>3
    });
    //some 检测数组中是否有满足条件的项 有则返回true 否则返回false
    //some 参数:callback this对象(执行 callback 时使用的 this 值。)
    //callback 参数:item index arr
    let someResult = arr.some(function(item,index,arr){
    return item>3
    });
    console.log(someResult,arr)
  • 相关阅读:
    LF 第三章 装饰器和迭代器相关
    Python 文件管理
    Python 强制类型转换
    安装模块
    LF 第三章
    pep8 Python编码规则
    Help on module pyclbr:
    Help on class timedelta in module datetime:
    Help on function meshgrid in module numpy.lib.function_base:
    Help on module matplotlib.cm in matplotlib:
  • 原文地址:https://www.cnblogs.com/tutao1995/p/11314762.html
Copyright © 2011-2022 走看看