JavaScript的slice方法无法正常运行

3

我正试图使用slice()函数克隆我的数组,然后删除一个元素。但是,每当我点击要删除的元素时,它会删除数组中除我点击的元素以外的所有内容。

以下是我的当前代码:

deleteContact(contacts: Contacts){
if (contacts === null || contacts === undefined) {
  return;
}

const pos = this.contacts.indexOf(contacts);
if (pos < 0) {
  return;
}

this.contacts = this.contacts.splice(pos, 1);
this.contactsListClone = this.contacts.slice();
this.contactListChangedEvent.next(this.contactsListClone);
}

1
你在克隆 contacts 之前从中删除了除一个之外的所有项。此外,你的问题中提到你正在使用 slice,但是你的代码使用的是 splice - user47589
可能是 Javascript splice not working 的重复问题。 - iceveda06
1个回答

11

splice返回已删除的元素,因此在此行代码之后,this.contacts仅有一个已删除的元素。

this.contacts = this.contacts.splice(pos, 1);

简单地制作它。

this.contacts.splice(pos, 1);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接