1:reduce应用场景:计算数组中所有值的总和
数组求和:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> </body> <script> //一堆变成一个,算总数 let arr = [12, 33, 66, 99] let result = arr.reduce(function(tmp, item, index) { return tmp + item }) console.log(result); </script> </html>
打印结果如下:
2:forEach循环遍历(迭代)
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> </body> <script> let arr = [12, 4, 6, 89, 2] arr.forEach(item => { console.log(item) }) </script> </html>
打印结果如下:
参数index
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> </body> <script> let arr = [12, 4, 6, 89, 2] //参数index arr.forEach((item,index) => { console.log(index+ ':' +item) }) </script> </html>
打印结果如下: