1、some,用于通过判断条件获得数组中的某一项,相比于 foreach 而言,foreach 在循环得到结果之后不会终止循环,会一直循环到数组结束,浪费性能,而 some 则通过 return true 终止循环。详情如下。
const array = ['苹果','香蕉','梨','榴莲','桃子']
// forEach 用法
array.forEach((item, index)=>{
if(item === '榴莲') {
console.log(index)
}
})
// some 用法
array.some((item, index) => {
if(item === '榴莲') {
console.log(index)
return true
}
})
2、every,用于数组中的每一项是否符合判断条件,返回布尔值,全部满足返回true,有一项不满足返回false。详情如下。
const array = [
{name:"苹果",state:true},
{name:"香蕉",state:false},
{name:"梨",state:true},
{name:"榴莲",state:true},
{name:"桃子",state:true}
]
const result = array.every(item => item.state)
console.log(result) // false
3、reduce, 累加器,用于把每次循环结果累加起来
const array = [
{name: "苹果", state: true, price: 10, count: 1},
{name: "香蕉", state: false, price: 20, count: 2},
{name: "梨", state: true, price: 30, count: 3},
{name: "榴莲", state: true, price: 40, count: 4},
{name: "桃子", state: true, price: 50, count: 5}
]
// 需求:计算勾选的水果总价
// 常规写法
let amt = 0 // 总价
array.filter(item => item.state).forEach(item => {
amt += item.price * item.count
})
// reduce写法
// 语法 reduce((计算结果, 当前循环量) => { }, 初始值)
array.filter(item => item.state).reduce((amt, item) => {
return amt += item.price * item.count
}, 0)
// 简写
array.filter(item => item.state).reduce((amt, item) => amt += item.price * item.count, 0)

7万+

被折叠的 条评论
为什么被折叠?



