我有一個包含 Id 列的串列。當用戶添加一個專案時,它從 3.1 開始,并在添加每個專案時繼續 3.2、3.3、3.4。
問題:如果用戶在最多 3.7 的串列中洗掉例如 3.3,則這些 Id 的順序將不是連續的。我正在嘗試使用以下內容遍歷 Id 以重新排序它們,從 3.1 開始作為串列的第一行。
這是洗掉功能:
const deleteItem = () => {
const currentArray = myArr;
for (var i = 0; i < currentArray .length; i ) {
if (currentArray [i] == selectedItem) {
currentArray .splice(i, 1);
}
setMyArr([...currentArray ]);
}
for(var i = 3.1; i < currentArray .length; i ){
i 0.1;
}
};
第一個for,洗掉專案并設定專案陣列,第二個for是我嘗試重置 Id 的順序。
我已經查看了幾個關于 SO 的解決方案,但沒有發現它們有用。
我該怎么做。
uj5u.com熱心網友回復:
您可以過濾要洗掉的專案,然后再次設定 ID,如下所示:
currentArray
.filter(item => item !== selectedItem) // Remove the selectedItem from the array
.map((item, idx) =>({...item, id:3.1 index * 0.1}) // Reset the ids sequentially
uj5u.com熱心網友回復:
陣列索引和長度不適用于十進制值。
我認為你想要做的是迭代陣列并根據第一個的 id 設定 id:
const finalArray = currentArray.map((item,index)=> ({...item, id:3.1 index * 0.1});
如對該問題的評論中所述index * 0.1,可能會出現四舍五入錯誤,因此您應該應用四舍五入。
(我假設您的專案是物件并具有 id 屬性)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/442923.html
標籤:javascript 反应 循环
下一篇:將數字添加到數字N次
