我有点被这个简单的代码弄糊涂了:
//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
知道为什么不起作用吗?
我注意到问题是您可能以错误的方式使用了splice
。
splice((方法通过移除或替换现有元素和/或就地添加新元素来更改数组的内容。要在不修改的情况下访问数组的一部分,请参阅slice((
但是在您的代码中,您试图将splice
的值分配给一个无效的值。
您可能混合了slice
和splice
。我认为在这种情况下,您应该使用slice
。
slice((方法将数组一部分的浅拷贝返回到从开始到结束(不包括结束(选择的新数组对象中,其中开始和结束表示该数组中项目的索引。原始数组不会被修改。
您应该使用findIndex
。我不知道你的数组是什么样子的,但在类似的情况下,如果你想从1和0的数组中删除第一个1,你可以写这样的东西:
const arr = [0,0,0,0,0,1,0,0,0];
arr.splice(arr.findIndex(e => e === 1), 1);
console.log(arr);
也许Array的filter
方法可以帮助您
cardData.likeData.likeUids.filter ((entry) => {
return entry !== uid;
});
如果您有许多uid要删除
你可以试试
cardData.likeData.likeUids.filter ((entry) => {
return uids.indexOf(entry) === -1;
});
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
我用你写的东西做了一小段代码,似乎可以做你想做的事:
更改UID将决定从数据中删除的内容。
let data = [1,2,3];
let uid = 1;
let foundUidIndex;
data.forEach ((entry, index) => {
if (entry === uid){
foundUidIndex = index;
console.log ("Found uid, index is " + foundUidIndex)
}
})
data.splice(foundUidIndex, 1);
console.log(data);