【问题标题】:alternatives for this forEach这个 forEach 的替代品
【发布时间】:2020-09-15 11:29:22
【问题描述】:

我有一些代码使用 forEach 循环遍历用户数组。在那个循环中,我再次使用 forEach 来循环他们的价格警报。看起来像这样

  user_data.users.forEach((user, index) => {
    if (user.id == id) {
      user.price_alerts.forEach((alert, alert_index) => {
        if (alert.symbol == symbol) {
          //remove alert
          user.price_alerts.splice(alert_index, 1);
        }
      });
    }
  });

但是这个问题不是删除所有带有“符号”的匹配项,而是删除一个。 我该如何解决 ?提前感谢

【问题讨论】:

  • Array.prototype.filter()
  • 是的,我已经阅读,但我不确定在这种情况下如何实现它。你能帮我弄清楚吗?
  • user.price_alerts.filter(alert => alert.symbol !== symbol);

标签: javascript arrays filter foreach splice


【解决方案1】:

如果您需要删除所有不满足某些条件的元素,请尝试使用filter方法:

let result = user.price_alerts.filter(alert => alert.symbol !== symbol);

更新:

user.price_alerts = user.price_alerts.filter(alert => alert.symbol !== symbol);

【讨论】:

  • 我可以在不将其分配给user.price_alerts.filter(alert => alert.symbol == symbol); 之类的新变量的情况下执行此操作(因为我想在满足条件时删除所有匹配的符号)
  • filter 不会修改现有数组,它会返回一个新数组,其中仅包含与谓词匹配的元素。您可以执行类似 user.price_alerts = user.price_alerts.filter(...) 的操作来替换现有警报
  • @KautilyaKondragunta testpossessed 是对的。请看我更新的答案
猜你喜欢
  • 2013-01-12
  • 2017-11-09
  • 2019-10-06
  • 2019-08-26
  • 2011-10-21
  • 1970-01-01
  • 2012-02-14
  • 1970-01-01
  • 2020-03-04
相关资源
最近更新 更多