【发布时间】:2022-01-13 16:44:08
【问题描述】:
我对这个非常简单的代码无法正常工作感到有些困惑:
//find the index to be removed
cardData.likeData.likeUids.forEach ((entry, index) => {
if (entry === uid){
uidFound = true
uidIndex = index
console.log ("Found uid, index is " + uidIndex)
//console shows correct index
}
})
let newLikeUids = cardData.likeData.likeUids.splice (uidIndex, 1)
//instead of deleting the found index, the element before the index is removed... for some reason
知道为什么这不起作用吗?
【问题讨论】:
-
请在脚本中提供必要的输入,以便我们运行和重现问题。
-
你真的应该使用 findIndex 而不是 forEach
-
另请注意,
splice返回已删除的元素,而不是删除的结果——这是原地发生的。 -
const index = cardData.likeData.likeUids.indexOf(uid); if (index > -1) { cardData.likeData.likeUids.splice(index, 1); } -
newLikeUids应该是什么?我认为这是真正的问题。
标签: javascript arrays splice