一:数组方法filter(过滤)
1:过滤掉不能被3整除的数,打印出来能被整除的数
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> </body> <script> //过滤器filter let arr = [12, 33, 66, 99, 5] let result = arr.filter(item => { if (item % 3 == 0) { return true; } else { return false; } }) console.log(result) </script> </html>
打印结果如下:
或者这样写,效果是一样的
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> </body> <script> let arr = [11, 33, 66, 99, 5] let result = arr.filter(item => { return item % 3 == 0; }) console.log(result) </script> </html>
打印结果如下:
2:过滤商品价格小于10000元的商品,打印大于10000元的商品
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> </body> <script> //商品列表 let arr = [{ title: '笔记本电脑', price: 12033 }, { title: '智能音箱', price: 99 }, { title: '鼠标', price: 33 }, { title: '单反摄像机', price: 20000 }, ] let result = arr.filter(item => item.price >= 10000); console.log(result) </script> </html>
打印结果如下:
二:数组方法map(映射)
一般写法
//一般写法 let arr=[12,5,8]; let result= arr.map(function(item){ return item*2; }) console.log(result)
箭头函数写法
//箭头函数 let arr=[10,5,8]; let result= arr.map(item=>{ return item*2; }) console.log(result)
去掉花括号的写法(只有一个return的时候,{}可以省略)
let arr=[10,5,9]; let result=arr.map(item=>item*2); console.log(result)
示例:判断数组所对应的的状态是否及格
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> </body> <script> let scroe = [12, 77, 88, 99, 33, 100, 59]; let result = scroe.map(item => item >= 60 ? '及格' : '不及格'); console.log(scroe) console.log(result) </script> </html>
三:数组方法reduce和forEach
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>
打印结果如下: