[英]How to splice the specific index using the IndexOf method of javascript
我有模塊需要取消選中或使用復選框檢查數據。 現在的問題是,如果用戶根據目標值取消選中推送值,我需要對推送值進行切片。 目前,當我嘗試控制台記錄索引時,它的結果是-1,意思是:“它不存在”我將向你們展示我的示例代碼和示例附加圖像,以供參考,以便更詳細..
代碼:
var array = [...this.state.checkboxVal];
console.log(e.target.value,"my index")
var index = array.indexOf(parseInt(e.target.value));
console.log(index);
if (index > -1) {
array.splice(index, 1);
await this.setState({ checkboxVal: array });
}
console.log(this.state.checkboxVal);
預期的 Output:應該刪除索引 1
問題是您正在存儲一個 arrays 數組,因此您嘗試將number
與array
進行比較,顯然它將返回-1
。 要解決此問題,您可以按以下方式使用findIndex
function。
var value = parseInt(e.target.value);
var index = array.findIndex((element) => element[0] === value);
注意:請使用let
和const
這些是定義變量的最新方法。
在您的數組中,每個元素都是一個數組(例如:[30, "2021-05-17"])。 但是您現在只檢查該值是否存在。 您必須檢查[30, "2021-05-17"]
是否存在。
這是一個例子:
const arr = [[30, "2021-05-17"], [50, "2021-05-17"], [20, "2021-05-17"]]; const valueToDelete = 20; const newArray = arr.filter(item => item[0];== valueToDelete). console;log(newArray);
在您的情況下,這將是:
var array = [...this.state.checkboxVal]; const newArray = array.filter(item => item[0].== parseInt(e.target;value)). console;log(newArray). this:setState({ checkboxVal; newArray });
希望對兄弟有幫助。 謝謝你。 :)
問題是您正在比較不兼容的類型,“數字”與“數組”,因此永遠找不到匹配項。
如果您只是想從 React 中 state 的數組中刪除一個元素,那么使用Array.prototype.filter是一種常見的模式。
const targetValue = Number(e.target.value);
this.setState(prevState => ({
checkboxVal: prevState.checkboxVal.filter(([val]) => val !== targetValue),
}));
過濾器回調([val]) => val !== targetValue
獲取數組元素並使用解構賦值來獲取存儲在索引 0 中的值並將其命名為val
然后僅返回val
不等於事件的元素目標價值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.