ES6数组中删除指定元素
知識點:
ES6從數(shù)組中刪除指定元素
findIndex()方法返回數(shù)組中滿足提供的測試函數(shù)的第一個元素的索引。否則返回-1。
arr.splice(arr.findIndex(item => item.id === data.id), 1)
http://louiszhai.github.io/2017/04/28/array/
1:js中的splice方法
splice(index,len,[item]) 注釋:該方法會改變原始數(shù)組。
splice有3個參數(shù),它也可以用來替換/刪除/添加數(shù)組內(nèi)某一個或者幾個值
index:數(shù)組開始下標(biāo) len: 替換/刪除的長度 item:替換的值,刪除操作的話 item為空
如:arr = ['a','b','c','d']
刪除 ---- item不設(shè)置
arr.splice(1,1) //['a','c','d'] 刪除起始下標(biāo)為1,長度為1的一個值,len設(shè)置的1,如果為0,則數(shù)組不變
arr.splice(1,2) //['a','d'] 刪除起始下標(biāo)為1,長度為2的一個值,len設(shè)置的2
替換 ---- item為替換的值
arr.splice(1,1,'ttt') //['a','ttt','c','d'] 替換起始下標(biāo)為1,長度為1的一個值為‘ttt’,len設(shè)置的1
arr.splice(1,2,'ttt') //['a','ttt','d'] 替換起始下標(biāo)為1,長度為2的兩個值為‘ttt’,len設(shè)置的1
添加 ---- len設(shè)置為0,item為添加的值
arr.splice(1,0,'ttt') //['a','ttt','b','c','d'] 表示在下標(biāo)為1處添加一項‘ttt’
想要的:定義一個數(shù)組ARR,保存已勾選上的數(shù)據(jù)ID,改變勾選框的狀態(tài)時從數(shù)組中刪除或添加數(shù)據(jù)ID,點擊批量刪除時,獲取數(shù)組ARR
操作:
1.頁面設(shè)置
// 全選
<th nz-th nzCheckbox>
<label nz-checkbox [(ngModel)]="_allChecked" [nzIndeterminate]="_indeterminate" (ngModelChange)="_checkAll($event)">
</label>
</th>
//單選
<td nz-td nzCheckbox>
<label nz-checkbox [(ngModel)]="data.checked" (ngModelChange)="_refreshStatus($event)" (click)="onSelect(data)">
</label>
</td>
2.全選操作觸發(fā)事件
// 初始化全選和全部取消的狀態(tài)
_allChecked = false; _indeterminate = false;
_bacthDelete =[];//定義一個數(shù)組,存放勾選的數(shù)據(jù)ID
// 點擊全選觸發(fā)的事件 _checkAll(value) { if (value) { this._displayData.forEach(data => { data.checked = true; this._bacthDelete.push(data.id); }, console.log(this._bacthDelete) ); } else { this._displayData.forEach(data => { data.checked = false; }, this._bacthDelete=[] ); console.log(this._bacthDelete) } this._refreshStatus(); }
3.點擊單個數(shù)據(jù)狀態(tài)
onSelect(data: FormData): void {
this.selectedTestId = data;
console.log(data);
if(!data.checked){
let arr = this._bacthDelete;
arr.splice(arr.findIndex(item => item.id === data.id), 1)
console.log(arr)
}else{
this._bacthDelete.push(data.id);
console.log( this._bacthDelete)
}
}
總結(jié)
以上是生活随笔為你收集整理的ES6数组中删除指定元素的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 氢氧化镁化学式(氯化镁化学式)
- 下一篇: 需要拆机拆键盘电脑键盘如何拆