全新的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' ] >