【问题标题】:Type-/JavaScript - array.indexOf always returns -1Type-/JavaScript - array.indexOf 总是返回 -1
【发布时间】:2017-03-07 21:33:08
【问题描述】:

我使用splice 函数从数组中删除一个元素,并使用indexOf 函数获取元素位置。

indexOf 总是返回-1,尽管数组中存在相同的元素。

我的代码(Angular2):

subToDelete : Subscription;
public unsubscribe(topic:string) {
    this.subToDelete = new Subscription(topic);
    console.log("DeleteIndex: ",this.subs.indexOf(this.subToDelete));
    this.subs.splice(this.subs.indexOf(this.subToDelete),1);
    console.log("SubTo Delete: ",this.subToDelete);
    this.subs.forEach(element => {
    console.log("Subscribed to: ",element);
    });
}

这是控制台输出,您可以在其中看到,应该删除的元素包含在数组中,但 indexOf 仍然返回 -1

http://imgur.com/a/HGz5c(不知怎么上传不了照片,这里是链接)

【问题讨论】:

  • 由于您的数组似乎存储对象并且indexOf 检查严格相等,因此您的new Subscription(topic) 永远不会等于已经存在的数组元素(因为您刚刚创建了一个不在数组之前)

标签: javascript arrays angular typescript


【解决方案1】:

您也可以使用Array.prototype.find(),它比map 函数需要更少的迭代:

let index: number;
this.subs.find((item, i) => { if (item.topic === topic) index = i });
this.subs.splice(index, 1);

【讨论】:

  • find 返回什么?
【解决方案2】:

您面临的问题是因为您试图在对象数组中进行搜索。这与文字数组不同。

你可以这样做

pos = this.subs.map(function(e) {
    return e.topic;
  })
  .indexOf(this.subToDelete.topic);

this.subs.splice(pos,1);

查看question 以获取有关该主题的更多信息。

【讨论】:

  • 如果主题不存在,indexOf 将返回 -1,因此 splice 将从 subs 中删除最后一个元素。您需要使用 if (pos > -1) 保护拼接操作
【解决方案3】:

您也可以使用Array.prototype.findIndex,我认为这是最简单的解决方案:

let index = this.subs.findIndex((item) => item.topic === topic);
if (index > -1) this.subs.splice(index, 1);

【讨论】:

    猜你喜欢
    • 2021-07-24
    • 2016-11-21
    • 2019-10-10
    • 2014-04-13
    • 2017-03-20
    • 2013-11-04
    • 2011-12-09
    • 2012-07-08
    • 1970-01-01
    相关资源
    最近更新 更多