【发布时间】:2021-09-25 20:18:47
【问题描述】:
我有一个无法解决的问题,我觉得有点奇怪。有一个对象列表foo,每个对象都有一个userId 属性,我想过滤该列表以删除包含userId 的所有项目,这些项目位于bar 数组中。
我使用了filter() 和some() 方法,但是,它们仅在bar 数组只有一个元素时才有效。
some() 在找到第一个匹配元素时是否会以某种方式阻止整个过滤器运行?
如果您能向我解释为什么这不起作用,我将不胜感激。
示例代码:
let foo = [
{
"userId": 1,
},
{
"userId": 2
},
{
"userId": 3
},
{
"userId": 4
}
];
let bar = [1, 2];
console.log(foo.filter(user => bar.some(id => id !== user.userId)));
预期值:
[
{
"userId": 3
},
{
"userId": 4
}
]
但我得到了:
[
{
"userId": 1,
},
{
"userId": 2
},
{
"userId": 3
},
{
"userId": 4
}
]
【问题讨论】:
-
"
some()方法对数组中存在的每个元素执行一次callbackFn函数直到找到callbackFn返回真值的元素(转换为布尔值后变为真的值)。如果找到这样的元素,some()立即返回真。否则,some()返回false。" -
使用
.includes()而不是.some()
标签: javascript arrays filtering