【问题标题】:JavaScript slice not workingJavaScript 切片不起作用
【发布时间】:2018-03-23 14:12:05
【问题描述】:

我正在尝试克隆我的数组,然后使用 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);
}

【问题讨论】:

  • 您正在从contacts克隆它之前删除除一个之外的所有项目。另外,您的问题说您使用的是slice,但您的代码使用的是splice

标签: javascript arrays angularjs


【解决方案1】:

splice 返回已删除元素,因此this.contacts 在这一行之后只有一个已删除元素

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

轻松搞定

this.contacts.splice(pos, 1);

【讨论】:

    猜你喜欢
    • 2017-05-04
    • 2018-05-23
    • 2017-03-17
    • 2014-04-18
    • 1970-01-01
    • 2011-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多