为什么Javascript map函数String.toLowerCase在nodejs 6中不起作用?

我正在阅读Ethan Brown的“Learning Javascript”一书。 有一个关于如何使用map函数将数组中的所有元素转换为小写的例子:

const cart = [ { name: "Widget", price: 9.95 }, { name: "Gadget", price: 22.95 }]; const names = cart.map(x => x.name); const lcNames = names.map(String.toLowerCase); 

如果我在Firefox(v51)浏览器控制台中运行它,但是如果我尝试在nodejs v6.9.4中运行它,则会得到:

 TypeError: undefined is not a function at Array.map (native) at repl:1:27 at sigintHandlersWrap (vm.js:22:35) at sigintHandlersWrap (vm.js:96:12) at ContextifyScript.Script.runInThisContext (vm.js:21:12) at REPLServer.defaultEval (repl.js:346:29) at bound (domain.js:280:14) at REPLServer.runBound [as eval] (domain.js:293:12) at REPLServer.<anonymous> (repl.js:545:10) at emitOne (events.js:101:20) 

如果我将lcNames赋值更改为nodejs的下列值,则运行正常:

 const lcNames = names.map(x => x.toLowerCase()); 

我检查了node6 vs Firefox 50的ES6 Javascript兼容性图表,他们似乎都支持相同的function。 那么为什么这本书的代码不能在nodejs中工作呢?

注意:

 names.map(String.toLowerCase); 

在Firefox中工作,因为它具有包含toLowerCase的 string通用方法 ,并logging在注释中:

stringgenerics是非标准的,不赞成使用,将来会被删除。 请注意,如果不使用下面提供的垫片,则不能依赖于它们。

最重要的是它们不是ECMAScript的一部分,所以在其他浏览器中可能不支持。 如果你想使用它,你可以有条件地添加一个pollyfill,尽pipe在MDN中添加了所有的generics方法都有一个shim。

 // Built-in support? console.log('Has built-in String.toLowerCase? ' + (typeof String.toLowerCase == 'function')); // Polyfill if not supported if (!String.toLowerCase) { String.toLowerCase = function(s) { return String(s).toLowerCase(); } } // Test it console.log(['A','B','C'].map(String.toLowerCase)) 

String.toLowerCase不存在。 但是, String.prototype.toLowerCase 。 但请记住, this将需要为该调用设置成功,而map它作为parameter passing 。 因此,这是最直接的做法:

 const lcNames = names.map(name => name.toLowerCase()); 

该函数在原型( String.prototype.toLowerCase )上定义,这意味着stringtypes的实例可以访问toLowerCase函数。

这就是为什么你可以通过const lcNames = names.map(x => x.toLowerCase());来访问这个函数const lcNames = names.map(x => x.toLowerCase());

另一方面,这是isFinite ,因为isFinite不是通过原型来定义的,而是通过Number本身定义的。

 const prices = cart.map(x => x.price); prices.map(Number.isFinite);