ES6刪除數組中指定元素,例:
let array = [1, 2, 3, 4];
//刪除2
array.splice(array.findIndex(item => item === 2), 1);
findIndex()方法滿足條件時返回數元素下標,否則返回-1
splice(index, len, [item])
- 刪除:[item]不設置,inde:刪除起始下標,len:刪除的長度(例:array.splice(1,1) 結果:[1, 2, 4])
- 替換:[item]爲替換的值,inde:替換起始下標,len:替換的長度(例:array.splice(1,2, ‘5’) 結果:[1, 5, 4])
- 添加:len設置爲0,[item]爲替換的值,index:添加起始下標(例:array.splice(1,0, ‘5’) 結果:[1, 5, 2, 3, 4])