3_数组的Map和reduce

本文介绍了JavaScript中map()和reduce()函数的使用方法,通过实例展示了如何遍历数组并操作其元素,以及如何将数组元素累加。重点讲解了如何在不改变原数组的情况下,利用map处理数组值和对象属性的变化。
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
//map属性的使用
    console.log("map属性的使用");
    //map方法自带循环,并且会把处理的值回填到响应的位置中去,但不会影响原本数组的值
        //使用map处理数组的值
        let arr = [1,2,3,4];
        var map = arr.map(function(currentValue){
            return currentValue*2;
        });
        console.log("原数组值不变");
        console.log(arr);
        console.log("map函数后得到的数组");
        console.log(map);
        //使用map处理对象属性
        let people = [{name:"zs",age:1},{name:"ls",age:2},{name:"ww",age:3},{name:"zl",age:4}];
        var peopleMap = people.map(function(currentValue){
            //这里不能直接写    return currentValue.age*2;这样peopleMap得到的值只有age没有name
            currentValue.age = currentValue.age*2
            return currentValue;
        });
        console.log("原数组值不变");
        console.log(people);
        console.log("map函数后得到的数组");
        console.log(peopleMap);
    </script>

<script>
    //reduce属性的使用
        console.log("reduce属性的使用");
        let arrs = [1,2,3,4];
        var rs = arrs.reduce(function(accumulator, currentValue){//累加器,当前元素
            return accumulator+currentValue;
        });
        console.log("原数组值不变");
        console.log(arrs);
        console.log("reduce函数后得到的值为数组所有元素的和");
        console.log(rs);
</script>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值