find()
定义和用法
find() 方法返回通过测试(函数内判断)的数组的第一个元素的值。
find() 方法为数组中的每个元素都调用一次函数执行:
当数组中的元素在测试条件时返回 true 时, find() 返回符合条件的元素,之后的值不会再调用执行函数。
如果没有符合条件的元素返回 undefined
注意: find() 对于空数组,函数是不会执行的。
注意: find() 并没有改变数组的原始值。
举个栗子
解释:
栗子项目采用vue全家桶+element-ui技术
栗子 适用于在表格中计算当行值的实时统计 以及 父级表格值得实时统计
countV(e, row, month) {
//计算输入后的差值
if (!isNaN(e.target.value) && !isNaN(this.oldV)) {
this.difference = e.target.value - this.oldV;
}
//当行计算total
row.total += this.difference;
//找到所有父节点,计算父节点的月合计和总合计
const setParentV = (pId) => {
const p = this.details.find((item) => item.subjectId === pId);
if (p) {
p[month.key] += this.difference;
p.total += this.difference;
setParentV(p.parentSubjectId);
}
};
setParentV(row.parentSubjectId);
//计算完后更新老值
if (!isNaN(e.target.value)) {
this.oldV = e.target.value;
}
},