一:數(shù)組方法filter(過濾)
1:過濾掉不能被3整除的數(shù),打印出來能被整除的數(shù)
<!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>
打印結(jié)果如下:

或者這樣寫,效果是一樣的
<!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>
打印結(jié)果如下:

2:過濾商品價(jià)格小于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: '鼠標(biāo)',
price: 33
},
{
title: '單反攝像機(jī)',
price: 20000
},
]
let result = arr.filter(item => item.price >= 10000);
console.log(result)
</script>
</html>
打印結(jié)果如下:

二:數(shù)組方法map(映射)
一般寫法
//一般寫法
let arr=[12,5,8];
let result= arr.map(function(item){
return item*2;
})
console.log(result)

箭頭函數(shù)寫法
//箭頭函數(shù)
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)

示例:判斷數(shù)組所對應(yīng)的的狀態(tài)是否及格
<!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>

三:數(shù)組方法reduce和forEach
1:reduce應(yīng)用場景:計(jì)算數(shù)組中所有值的總和
數(shù)組求和:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
</body>
<script>
//一堆變成一個,算總數(shù)
let arr = [12, 33, 66, 99]
let result = arr.reduce(function(tmp, item, index) {
return tmp + item
})
console.log(result);
</script>
</html>
打印結(jié)果如下:

2:forEach循環(huán)遍歷(迭代)
<!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>
打印結(jié)果如下:

參數(shù)index
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
</body>
<script>
let arr = [12, 4, 6, 89, 2]
//參數(shù)index
arr.forEach((item,index) => {
console.log(index+ ':' +item)
})
</script>
</html>
打印結(jié)果如下:
