假设我有一个 Set
作为查找表。
const myset = new Set(["key1", "key2", "key3", "keepMe"]);
我想过滤 myset
中的其他一些键(例如 mykeys
)的另一个数组。
const mykeys = ["ignoreMe", "keepMe", "ignoreMeToo", "key2"];
问题:
为什么我必须使用
const filtered = mykeys.filter(k => myset.has(k))
而不是
const filtered = mykeys.filter(myset.has)
// TypeError: Method Set.prototype.has called on incompatible receiver undefined
也就是说,为什么我必须在过滤器中创建匿名 lambda 函数? keys.has
具有相同的签名(参数 - 元素,返回 bool 值)。一位 friend 告诉我这与this
有关。
而 mykeys.map(console.log)
工作时没有错误(尽管没有多大用处)。
我遇到了这个article at MDN我仍然不明白为什么“'myset'没有被捕获为这样”。我理解解决方法,但不知道“为什么”。任何人都可以用一些细节和引用以人性化的方式解释它吗?
更新:感谢大家的回复。也许我并不清楚我在问什么。我确实了解解决方法。
@charlietfl 明白了。这是his comment ,我正在寻找的东西:
Because filter() has no implicit
this
where asset.has
needs to have properthis
context. Calling it inside anonymous function and manually adding argument makes the call self contained.
最佳答案
您可以使用Array#filter
的thisArg
使用 set 和 has
的原型(prototype)作为回调。
此模式不需要绑定(bind) Set
的实例到原型(prototype),因为
If a
thisArg
parameter is provided tofilter
, it will be used as the callback'sthis
value. Otherwise, the valueundefined
will be used as its this value. Thethis
value ultimately observable bycallback
is determined according to the usual rules for determining the this seen by a function.
const
myset = new Set(["key1", "key2", "key3", "keepMe"]),
mykeys = ["ignoreMe", "keepMe", "ignoreMeToo", "key2"],
filtered = mykeys.filter(Set.prototype.has, myset);
console.log(filtered);
关于javascript - 在 Array.filter 中使用 Set.has - 不兼容的接收器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50544029/