gpt4 book ai didi

javascript - splice 在从数组中删除条目时创建 NULL 条目

转载 作者:行者123 更新时间:2023-12-03 02:42:08 25 4
gpt4 key购买 nike

在我的 Angular5 应用程序中,当我尝试使用 splice 关键字从包含在 selectedPersonArray 中的 peoples 数组中删除条目时,有时会在 peoples 数组中创建空条目。我完成的代码如下所示:

import { Component } from '@angular/core';
import { DragulaService } from 'ng2-dragula/ng2-dragula';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {


selectedPersonArray = [];
peoples = [
{
id: 7,
firstName: 'Sobin 7',
lastName: 'Thomas 7'
}
];
people = [
{
id: 1,
firstName: 'First Name 1',
lastName: 'Last Name 1'
},
{
id: 2,
firstName: 'First Name 2',
lastName: 'Last Name 2'
},
{
id: 3,
firstName: 'First Name 3',
lastName: 'Last Name 3'
},
{
id: 4,
firstName: 'First Name 4',
lastName: 'Last Name 4'
}
];

toggleItemInArr(arr, item) {
const index = arr.indexOf(item);
index === - 1 ? arr.push(item) : arr.splice(index, 1);
}

addThisPersonToArray(person: any, event) {
if (!event.ctrlKey) {
this.selectedPersonArray = [];
}

this.toggleItemInArr(this.selectedPersonArray, person);
}

isPersonSelected(person: any) {
return (this.selectedPersonArray.indexOf(person) !== -1);
}

constructor(private dragula: DragulaService) {
dragula.setOptions('second-bag', {
copy: function (el, source) {
return source.id === 'source';
},

removeOnSpill: true,

copySortSource: false,
accepts: function(el, target, source, sibling) {
return target.id !== 'source';
}
});


}
ngOnInit() {
this.dragula
.out
.subscribe(value => {

for(let select of this.selectedPersonArray){
let i= 0;
for (let entry of this.peoples) {
if(entry.id == select.id){
let index = this.people.indexOf(select.id);
if (this.peoples.length >0){
this.peoples.splice(i, 1);
}
}
i++;
}
}
console.log("on after loop "+JSON.stringify( this.peoples));
this.selectedPersonArray.length = 0;

});
}
}

app.component.html

<table border=1 bgcolor="yellow">
<tbody id ='source' [dragula]='"second-bag"' [dragulaModel]="people">
<tr *ngFor="let person of people" >
<td>{{person.id}}</td>
<td>{{person.firstName}}</td>
<td>{{person.lastName}}</td>
</tr>
</tbody>
</table>




<table border=2>
<tbody id ='dest' [dragula]='"second-bag"' [dragulaModel]="peoples">
<tr *ngFor="let person of peoples" (click)="addThisPersonToArray(person, $event)" [class.active]="isPersonSelected(person)">
<td>{{person.id}}</td>
<td>{{person.firstName}}</td>
<td>{{person.lastName}}</td>
</tr>
</tbody>
</table>

实际上我想要的是删除使用控制键从 ng2-dragular secondary-bag 的“dest”容器中选择的多个项目。它正在工作,但它也创建空条目

最佳答案

你能试试这个吗?

this.peoples
.filter(people => !this.selectedPersonArray
.find(selectdPeople => people.id === selectdPeople.id)
);

关于javascript - splice 在从数组中删除条目时创建 NULL 条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48286506/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com