admin管理员组

文章数量:1287956

I am trying to clone my array and then delete one element from it by using the slice() function. However, whenever I click on the element I want to be deleted, it deletes everything in the array except for the one that I click.

Here is my current code:

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);
}

I am trying to clone my array and then delete one element from it by using the slice() function. However, whenever I click on the element I want to be deleted, it deletes everything in the array except for the one that I click.

Here is my current code:

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);
}
Share Improve this question edited Mar 23, 2018 at 14:16 Strille 5,7813 gold badges27 silver badges40 bronze badges asked Mar 23, 2018 at 14:12 shae01shae01 611 gold badge2 silver badges5 bronze badges 2
  • 1 You are removing all the items except one from contacts before cloning it. Also, your question says you're using slice, but your code uses splice – user47589 Commented Mar 23, 2018 at 14:14
  • Possible duplicate of Javascript splice not working – iceveda06 Commented Mar 23, 2018 at 14:34
Add a ment  | 

1 Answer 1

Reset to default 11

splice returns deleted elements, so this.contacts has only one deleted elements after this line

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

simply make it

this.contacts.splice(pos, 1);

本文标签: arraysJavaScript slice not workingStack Overflow