[英]Javascript splice removes wrong element
我對這個非常簡單的代碼無法正常工作感到有些困惑:
//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
。 我不知道你的數組是什么樣子,但在類似的情況下,你想從 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);
我注意到問題是您可能以錯誤的方式使用splice
。
splice() 方法通過刪除或替換現有元素和/或在適當位置添加新元素來更改數組的內容。 要訪問數組的一部分而不修改它,請參閱 slice()
但是在您的代碼中,您試圖將splice
的值分配給一個不起作用的值。
您可能會混合slice
和splice
。 我認為在這種情況下,您應該改用slice
。
slice() 方法將數組的一部分的淺拷貝返回到一個新數組 object 中,該數組從開始到結束(不包括結束)選擇,其中開始和結束表示該數組中項目的索引。 原始數組不會被修改。
也許 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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.