【问题标题】:How do I use Array.prototype.filter() inside a forEach loop [duplicate]如何在 forEach 循环中使用 Array.prototype.filter() [重复]
【发布时间】:2021-08-18 16:03:10
【问题描述】:

我在这里遇到了很多关于使用 filter() 方法的答案,但是没有一个涵盖在循环中使用它。我设法解决了这个问题,但是我认为最好在此处包含我的答案,以防其他人遇到此问题。

我有两个对象数组,linksindex。每个对象都有两个属性,hreftext

var links = [
      { href: '/accessibility', text: 'Accessibility'},
      { href: '/accessibility/accessibility-statement', text: 'Accessibility Statement'},
      { href: '/accessibility/color', text: 'Color and Contrast'},
      { href: '/accessibility/images', text: 'Images'},
      { href: '/accessibility/inclusive-language', text: 'Inclusive language'}
  ];
  var index = [
    { href: '/accessibility-statement', text: 'Accessibility Statement' },
    { href: '/accessibility', text: 'Accessibility' },
    { href: '/accessibility/colour', text: 'Colour and contrast' },
    { href: '/accessibility/images', text: 'Images' },
    { href: '/accessibility/inclusive-language', text: 'Inclusive language' },
    { href: '/accessibility/keyboard', text: 'Keyboard' },
    { href: '/cookies', text: 'Cookies' },
    { href: '/get-started', text: 'Get started' },
    { href: '/get-started/project', text: 'Production' },
    { href: '/get-started/prototyping', text: 'Prototyping' },
    { href: '/styles/colour', text: 'Colour' },
    { href: '/styles/images', text: 'Images' },
    { href: '/styles/typography', text: 'Typography' },
    { href: '/working-on-your-project', text: 'Working on your project' }
  ];

我正在编写一个函数,它解析索引数组并在它在链接数组中找到匹配的对象时删除元素。我不能直接这样做,因为 JS 中两个具有完全相同属性的对象不被认为是相等的,所以我只是基于 href 属性,这很好。

function removeLinksFromIndex(links, index) {
  links.forEach(element => {          // for each element in links array...
    index = index.filter(entry => {   // filter out entries where...
        element.href == entry.href    // the href attributes match
    });
  });

  return index;
}

此代码应该按照 cmets 的建议执行,但事实并非如此。我只剩下最后一个空数组。我在每个阶段都输出了索引,除了最后一次迭代更改为[]之外,每次都没有变化。

【问题讨论】:

  • 另外,我认为这就像const result = index.filter(i => !links.some(x => i.href == x.href)); 一样简单,并且没有您的答案可能带来的不良副作用

标签: javascript arrays filter foreach


【解决方案1】:

我最初的代码很接近,但不太正确。

首先,过滤器方法返回一个对象数组,其中对象满足指定条件。所以我想返回element.href != entry.href的对象。

其次,如果我们从过滤器函数中删除花括号,代码将起作用。当条件像以前一样在单独的行上时,它不起作用。我不知道为什么,但也许其他人可以解释一下?

function removeLinksFromIndex(links, index) {
  links.forEach(element => {
    index = index.filter(entry => element.href != entry.href);
  });

  return index;
}
// This code works!

【讨论】:

  • 当您在过滤器函数中使用{...} 时,那些{...} 成为函数的主体 - 因为它没有return 语句,所以您隐式返回undefined,即一个虚假的值,因此过滤器失败并过滤掉所有内容。如果没有花括号,箭头函数将隐式返回 => 之后的表达式
猜你喜欢
  • 1970-01-01
  • 2020-10-18
  • 1970-01-01
  • 2016-07-28
  • 1970-01-01
  • 2020-04-11
  • 2014-08-25
  • 2017-02-12
  • 1970-01-01
相关资源
最近更新 更多