如何实现向数组插入对象时自动递增order值?
解决方案
要实现点击Add按钮时,新对象的order值为数组现有最大order+1(空数组时从0开始),只需修改TS中的add方法,先计算当前数组的最大order值,再生成新对象即可。
方法一:使用Math.max结合数组长度判断
this.templatesDto = []; add() { // 计算当前数组的最大order值,空数组时默认-1 const maxOrder = this.templatesDto.length ? Math.max(...this.templatesDto.map(item => item.order)) : -1; this.templatesDto.push({ id: 0, order: maxOrder + 1 }); }
方法二:使用reduce(更简洁)
利用reduce遍历数组计算最大值,初始值设为-1,无需额外判断数组是否为空:
this.templatesDto = []; add() { const maxOrder = this.templatesDto.reduce((prev, curr) => Math.max(prev, curr.order), -1); this.templatesDto.push({ id: 0, order: maxOrder + 1 }); }
逻辑说明
- 当数组为空时,
reduce直接返回初始值-1,加1后得到0,符合需求 - 当数组非空时,
reduce遍历所有对象,逐个比较并保留最大的order值,最终加1得到新对象的order Math.max(...this.templatesDto.map(item => item.order))通过map提取所有order值,再用展开运算符传入Math.max获取最大值
内容的提问来源于stack exchange,提问作者Tim Launders
相关产品推荐
相关产品推荐

