【问题标题】:Remove one object from JS Array从 JS 数组中删除一个对象
【发布时间】:2017-01-07 20:41:56
【问题描述】:

我有以下功能:

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

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

如何告诉这个函数只过滤一张具有相同 ID 的卡片?比如,找一张 id 为 5 的牌,把那张从我手上剪下来,然后把其他的牌都留在我的手上?

【问题讨论】:

  • 我会说你的逻辑有问题。如果您有对象列表,无论您如何向用户显示它,但对于您(开发人员),每个项目都应该有唯一的 id。它将为您避免未来的很多问题
  • 我想这是公平的......它不适合客户或任何东西,只是一件快速而肮脏的事情。

标签: javascript arrays typescript


【解决方案1】:

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

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

  2. 移除对象

演示:

// Find index
var index = cards.findIndex(function (c) {
    return c.id === cardId;
})

// Remove if exists
if (index >= 0) {
    cards.splice(index, 1)
}

JSFiddle Example

【讨论】:

    【解决方案2】:

    不幸的是,我不认为有一个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);
    }
    

    【讨论】:

      猜你喜欢
      • 2015-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-08
      • 2021-03-21
      相关资源
      最近更新 更多