从JS Array

时间:2017-01-07 20:41:57

标签: javascript arrays typescript

我有以下功能:

private removeOneCard(id) {
  this.cards = this.cards.filter(
    card => card.id != id);
}

我已经能够过滤掉所有具有相同ID的对象。问题是我有一些具有相同id的对象(用于纸牌游戏)。我不是要对所有卡片进行复制,而是跟踪人们手中仍然存在多少相同类型的卡片。

如何判断此功能只能过滤其中一张ID相同的卡?如上所示,找到一张id为5的卡片,从我的手中切下那张卡片,然后把所有其他的卡片放在我手里?

2 个答案:

答案 0 :(得分:3)

您可以将其分为两个步骤:

  1. 查找第一次出现的索引。

  2. 删除对象

  3. 演示:

    // Find index
    var index = cards.findIndex(function (c) {
        return c.id === cardId;
    })
    
    // Remove if exists
    if (index >= 0) {
        cards.splice(index, 1)
    }
    

    JSFiddle Example

答案 1 :(得分:1)

不幸的是,我不认为有一个Array.prototype功能可以实现你想要的功能。

这可能是最简洁的陈述性方法。

private removeOneCard(id) {
  // Grab the index of the first card whose ID matches the input ID
  const removeIdx = this.cards.findIndex((card) => card.id === id);
  // Remove that index from the array
  this.cards = this.cards.filter((card, idx) => idx !== removeIdx);
}
相关问题