【发布时间】:2021-08-18 16:03:10
【问题描述】:
我在这里遇到了很多关于使用 filter() 方法的答案,但是没有一个涵盖在循环中使用它。我设法解决了这个问题,但是我认为最好在此处包含我的答案,以防其他人遇到此问题。
我有两个对象数组,links 和 index。每个对象都有两个属性,href和text。
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