1.map forEach
1.map 循环遍历每一项,返回一个新的数组
例: 购物车商品小计:
//购物车
var cart=[
{"id":101,"name":"大米","count":1,"price":3.3,"check":1},
{"id":102,"name":"小米","count":2,"price":3.3,"check":1},
{"id":103,"name":"二米","count":3,"price":3.3,"check":1},
]
//每个购物车中的小计
var cartPrices =cart.map(item=>{
return (item.count*item.price).toFixed(2)
})
console.log(cartPrices);
2.forEach 循环遍历每一项,并不返回值
例:计算商品价格的总和:
//购物车
var cart=[
{"id":101,"name":"大米","count":1,"price":3.3,"check":1},
{"id":102,"name":"小米","count":2,"price":3.3,"check":1},
{"id":103,"name":"二米","count":3,"price":3.3,"check":1},
]
//每个购物车中的小计
var cartPrices = cart.map(item=>{
return (item.count*item.price).toFixed(2)
})
//计算总和
var totalPrice = 0
cartPrices.forEach((item,index)=>{
totalPrice+=parseFloat(item);
})
console.log(totalPrice.toFixed(2));
2.filter 过滤出正确的那一项
例: 显示购物车信息
//商品ID
var id = 101;//101胶水'.'
//购物车
var cart=[
{"id":101,"name":"大米","count":1,"price":3.3,"check":1},
{"id":102,"name":"小米","count":2,"price":3.3,"check":1},
{"id":103,"name":"二米","count":3,"price":3.3,"check":1},
]
//过滤出该商品信息
var goods = cart.filter(item=>{
return item.id == id;
})
console.log(goods);
3.some 和 every 过滤每一项是否有正确的
1.some 如果有满足条件返回true不在向下执行 ,如果没有满足条件返回false
例: 购物车是否选中
//商品ID
var id = 101;//101胶水'.'
//购物车
var cart=[
{"id":101,"name":"大米","count":1,"price":3.3,"check":0},
{"id":102,"name":"小米","count":2,"price":3.3,"check":1},
{"id":103,"name":"二米","count":3,"price":3.3,"check":1},
]
//过滤购物车商品是否选中状态
var ischeck = cart.some(item=>{
if(item.id == id){
return item.check;
}
})
console.log(ischeck)
2.every 数组的每一项是否都满足条件返回true,否则返回false
例:购物车商品是否全选状态
//商品ID
var id = 101;//101胶水'.'
//购物车
var cart=[
{"id":101,"name":"大米","count":1,"price":3.3,"check":1},
{"id":102,"name":"小米","count":2,"price":3.3,"check":0},
{"id":103,"name":"二米","count":3,"price":3.3,"check":1},
]
//过滤购物车商品是否选中状态
var isallcheck = cart.every(item=>{
return item.check;
})
console.log(isallcheck)