JavaScript如何查找数组内嵌套对象索引并删除最高urgency值对象
问题根因
indexOf方法对对象这类引用类型是按内存地址做严格匹配,你传入的是序列化后的字符串"outputNewtask",和数组内的对象完全不匹配,必然返回-1。- 即使直接传入
maxObj作为indexOf参数,只要数组中存在多个相同stockUrgency的对象、或者对象是引用不同的同结构数据,也会出现匹配失败的问题。
正确实现
方案1:单次遍历(性能最优,仅遍历1次数组)
function newTask() { // 空数组边界处理 if (taskList.length === 0) return null; let maxUrgency = taskList[0].stockUrgency; let maxIndex = 0; // 遍历找最高优先级的索引 for (let i = 1; i < taskList.length; i++) { if (taskList[i].stockUrgency > maxUrgency) { maxUrgency = taskList[i].stockUrgency; maxIndex = i; } } // 取出目标对象并从原数组移除 const [maxObj] = taskList.splice(maxIndex, 1); // 序列化逻辑 const outputNewtask = JSON.stringify(maxObj, null, 4); console.log(outputNewtask); return maxObj; }
方案2:reduce写法
如果你习惯用reduce实现,可以在迭代时同步记录索引:
function newTask() { if (taskList.length === 0) return null; // reduce同时存储最大值对象和对应索引 const { value: maxObj, index: maxIndex } = taskList.reduce((max, current, index) => { return current.stockUrgency > max.value.stockUrgency ? { value: current, index } : max; }, { value: taskList[0], index: 0 }); taskList.splice(maxIndex, 1); const outputNewtask = JSON.stringify(maxObj, null, 4); console.log(outputNewtask); return maxObj; }
注意事项
如果数组中存在多个相同最高stockUrgency的对象,上述实现默认取第一个出现的对象,如果你需要取最后一个,把判断条件中的>改为>=即可。
内容的提问来源于stack exchange,提问作者Sigurd Horsholt Kristensen
相关产品推荐
相关产品推荐

