javascript – 为什么我需要在node.js中写“function(value){return my_function(value);}”作为回调?

全新的JS,所以请原谅,如果这是令人难以置信的明显.

假设我想使用映射字符串的功能f过滤字符串列表 – >布尔.这样做:

filteredList = list.filter(function(x) { return f(x); })

这失败了:

filteredList = list.filter(f)

为什么???

代码示例:

~/projects/node (master)$node
> var items = ["node.js","file.txt"]
undefined
> var regex = new RegExp('\\.js$')
undefined
> items.filter(regex.test)
TypeError: Method RegExp.prototype.test called on incompatible receiver undefined
    at test (native)
    at Array.filter (native)
    at repl:1:8
    at REPLServer.self.eval (repl.js:110:21)
    at Interface.<anonymous> (repl.js:239:12)
    at Interface.EventEmitter.emit (events.js:95:17)
    at Interface._onLine (readline.js:202:10)
    at Interface._line (readline.js:531:8)
    at Interface._ttyWrite (readline.js:760:14)
    at ReadStream.onkeypress (readline.js:99:10)
> items.filter(function(value) { return regex.test(value); } )
[ 'node.js' ]
>

解决方法

您正在传递对“测试”函数的引用,但是当它被调用时,正则表达式对象将不在其周围.换句话说,在“测试”的内部,这个值将是未定义的.

你可以避免:

items.filter(regex.test.bind(regex))

.bind()方法将返回一个永远以“regex”值运行的函数.

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...