为什么我在尝试使用 Array.include 作为 Javascript 中 Array.filter 的函数时出现错



最近在用javascript处理项目时,我尝试了类似于这个片段的东西。我很惊讶地发现它不起作用,而是抛出了一个错误。

const test = [1, 2, 3, 4];
const something = [1, 2, 3, 4, ,5, 6, 7, 8].filter(test.includes);
console.log(something);
TypeError: Cannot convert undefined or null to object
    at includes (<anonymous>)
    at Array.filter (<anonymous>)
    at evalmachine.<anonymous>:3:45
    at Script.runInContext (vm.js:74:29)
    at Object.runInContext (vm.js:182:6)
    at evaluate (/run_dir/repl.js:133:14)
    at ReadStream.<anonymous> (/run_dir/repl.js:116:5)
    at ReadStream.emit (events.js:180:13)
    at addChunk (_stream_readable.js:274:12)
    at readableAddChunk (_stream_readable.js:261:11)

这是一个JavaScript错误还是我误解了这里的东西。以下代码片段工作正常:

const test = [1, 2, 3, 4];
const something = [1, 2, 3, 4, ,5, 6, 7, 8].filter(item => test.includes(item));
console.log(something);

和:

const test = [1, 2, 3, 4];
const someFunc = theThing => test.includes(theThing);
const something = [1, 2, 3, 4, ,5, 6, 7, 8].filter(someFunc);
console.log(something);

当我很容易看到模式时,努力实现更实用的编程风格和无点,这似乎是一种不一致。

编辑:这不是重复的。我不需要澄清This,只需要在包含函数的上下文中如何处理它。

您可以使用Array#filterthisArg和对象函数的原型。

const test = [1, 2, 3, 4];
const something = [1, 2, 3, 4, ,5, 6, 7, 8].filter(Array.prototype.includes, test);
console.log(something);

但是Array#includes还有第二个参数fromIndex,它由过滤器函数传递,那就是索引,这可能是不需要的。

在这种情况下,最好使用直接样式。

const test = [1, 2, 3, 4];
const something = [1, 2, 3, 4, ,5, 6, 7, 8].filter(v => test.includes(v));
console.log(something);

test.includes计算指向函数的引用,并通过它丢失其上下文(又名this(。

 const fn = test.includes;
 fn(1); // doesnt work
 fn.call(test, 1); // does work as you explicitly set `this`.

您可以使用filter的第二个参数轻松修复它,

 .filter(test.includes, test)

最新更新