JavaScript如何通过元素值而非索引删除数组中的对应元素
解决方案
你完全可以使用splice方法实现需求,只需要先找到目标值在currentMaterialsId数组中对应的索引,再把这个索引传给splice作为第一个参数即可。
你之前的写法错误原因是splice的第一个参数要求是待操作数组本身的元素索引,而不是元素值,也不是其他对象里的属性索引,直接传id值当然匹配不到正确的位置。
单条指定值删除示例(比如删除值为2的元素)
const targetId = 2; // 查找目标值在currentMaterialsId中对应的索引 const targetIndex = currentMaterialsId.indexOf(targetId); // 仅当目标值存在时执行删除,避免索引无效时报错 if (targetIndex !== -1) { currentMaterialsId.splice(targetIndex, 1); }
结合你的业务场景使用
// 先从业务对象中取到需要删除的id值 const materialId = dashboard.sheets[selectedSheet].materialProperties[materialIndex].id; // 查找该id在currentMaterialsId中的索引 const targetIndex = currentMaterialsId.indexOf(materialId); if (targetIndex !== -1) { currentMaterialsId.splice(targetIndex, 1); }
批量删除多个匹配值的写法
如果需要一次性删除所有和materials中id匹配的元素,推荐倒序遍历数组避免删除操作导致的索引偏移问题:
// 先收集所有需要删除的id const toDeleteIds = Object.values(materials).map(item => item.id); // 倒序遍历待操作数组 for (let i = currentMaterialsId.length - 1; i >= 0; i--) { if (toDeleteIds.includes(currentMaterialsId[i])) { currentMaterialsId.splice(i, 1); } }
内容的提问来源于stack exchange,提问作者Lawrence Michael
相关产品推荐
相关产品推荐

