【Vue】2-12、数组

1. いくつかのループ

const arr = ['Jack','Mike','Judy','Andy']
/**
arr.forEach((item,index) => {
	if(item === 'Mike'){
		// forEach() 方法循环会把数组循环个遍之后才停止,中间无法停止,对性能消耗(浪费)较大
        console.log(index)
    }
})
*/
arr.some((item,index) => {
    if(item === 'Mike'){
        console.log(index)
        // 找到对应的项之后,通过 return 终止循环,节省性能消耗
        return true
    }
})

2. ループごと 

// 若数组中的每一项都满足条件则返回 true,若有一项不满足则返回 false
const fruits = [
    {id:1, name: '苹果', status: true},
    {id:2, name: '菠萝', status: true},
    {id:3, name: '香蕉', status: true},
    {id:4, name: '橙子', status: true},
]
console.log(fruits.every(item => item.status))

3.reduceメソッド 

const fruits = [
    {id:1, name: '苹果', status: true, price:10, count:2 },
    {id:2, name: '菠萝', status: true, price:15, count:3 },
    {id:3, name: '香蕉', status: false, price:20, count:5 },
    {id:4, name: '橙子', status: true, price:10, count:2 },
]
/**
	let total = 0;
	fruits.filter(item => item.status).forEach(item => {
		total += item.price * item.count
	})
	console.log(total)
*/

// reduce((累加的结果,循环项) => { },初始值)
/**
	const res = fruits.filter(item => item.status).reduce((total,item) => {
		total += item.price * item.count
	},0)
*/
// 简写:
const res = fruits.filter(item => item.status).reduce((total,item) =>  total += item.price * item.count,0)
console.log(res)

一枚の葉は秋を知る、謎と神秘

おすすめ

転載: blog.csdn.net/weixin_43551213/article/details/135946690