如何通过license属性从JavaScript数组中移除无引用的目标对象
你出现报错的核心原因是 Array.findIndex() 方法要求传入的参数是回调函数,你之前直接传入GetIdentifier返回的license字符串,JS会尝试将该字符串作为函数执行,自然触发“不是函数”的报错。
正确实现方式
方案1:使用findIndex + splice修改原数组
适合需要保留原数组引用、只删除指定项的场景:
// 1. 先获取要删除的目标license值 const targetLicense = GetIdentifier(global.source, 'license').toString() // 2. 查找目标项的索引 const deleteIndex = playersList.findIndex(item => item.license === targetLicense) // 3. 存在对应项时执行删除 if (deleteIndex > -1) { playersList.splice(deleteIndex, 1) }
方案2:使用filter生成新数组
写法更简洁,适合不需要保留原数组引用的场景:
const targetLicense = GetIdentifier(global.source, 'license').toString() playersList = playersList.filter(item => item.license !== targetLicense)
两种方案都可以实现按license删除数组元素的需求,可根据你的实际代码场景选择。
内容的提问来源于stack exchange,提问作者Sem Nombre
相关产品推荐
相关产品推荐

