JavaScript

forEach、map、reduce

2021-08-23  本文已影响0人  生爱_存在

arr.reduce(callback, initialValue) 迭代数组的所有项,累加器,数组中的每个值(从左到右)合并,最终计算为一个值

arr.map(callback) 映射数组(遍历数组),有return 返回一个新数组

        let arr1 = [1, 2, 3, 4, 5]
        let arr2 = arr1.map((item, index, array) => {
            array[index] = item + 10; // 原数组每一项 + 10,会改变原数组;
            item += 20;
            return item;
        })
        console.log(arr1); // [11, 12, 13, 14, 15]
        console.log(arr2); // [21, 22, 23, 24, 25]

arr.forEach(callback) 遍历数组,无return

        let arr = [1, 2, 3, 4, 5]
        arr.forEach((item, index, array) => {
            array[index] = item + 10; // 原数组每一项 + 10,会改变原数组;
            item += 10;
            console.log(`value:${item}    index:${index}     array:${array}`)
        })

两个数组中相同元素、大数组中不包含小数组部分、一行代码数组去重
数组方法

上一篇 下一篇

猜你喜欢

热点阅读