时间:2022/01/11
map函数:本身具有循环和填回的作用。
reduce函数:可以对数组的每个元素进行累加等操作。
示例代码如下:
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <meta http-equiv="X-UA-Compatible" content="IE=edge"> 6 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 7 <title>Document</title> 8 </head> 9 <body> 10 11 <script> 12 13 // map函数具有循环和填回的作用 14 let arr = [1, 2, 3, 4, 5]; 15 let newarr = arr.map(function(element){ 16 return element * 2; 17 }); 18 // 通过箭头函数,可以简写成下面的形式 19 // let newarr = arr.map(element => element * 2); 20 console.log(newarr); 21 22 // 使用map对对象进行操作 23 let person = [{name:"马驰", age:15}, {name:"展展", age:16}, {name:"黄黄", age:12}]; 24 let newperson = person.map(element => { 25 element.age += 1; 26 return element; 27 }); 28 console.log(newperson); 29 30 // reduce 31 let arr1 = [1, 2, 3, 4, 5]; 32 let sum = arr1.reduce((a, b) => { 33 return a + b; 34 }); 35 36 console.log("sum = " + sum); 37 38 </script> 39 40 </body> 41 </html>