1.直接用reduce
备注: 如果
var arr = [
{
name: 'hua',
age: '18'
},
{
name: 'chuan',
age: 16
},
{
name: 'test',
age: 16
}
]
const res = []
const total = arr.reduce((pre, cur) => {
return +pre + (+cur.age||0) // 如果age不是动态的,可以不加||0,这里是因为项目里面我的age是input动态输入的哈
}, 0) || 0
console.log(total) // 50
2.用forEach
var arr = [
{
name: 'hua',
age: '18'
},
{
name: 'chuan',
age: 16
},
{
name: 'test',
age: 16
}
]
let res = 0
arr.forEach((item) => {
res+= +item.age
})
console.log(res, 'res') // 50
每天都要好好生活呀-_-