startsWith在Node.js中:TypeError:undefined不是一个函数

我在Node.js中使用startsWith得到一个错误

脚本sw.js

//startswith var str = 'Sein oder nicht sein, dass ist hier die Frage'; console.log(str.startsWith('Sein oder')); // true console.log(str.startsWith('nicht sein')); // false console.log(str.startsWith('nicht sein', 10)); // true 

脚本的输出:

 /Users/.../sw.js:2 = 'Sein oder nicht sein, dass ist hier die Frage'; console.log(str.startsWith ^ TypeError: undefined is not a function at Object.<anonymous> (/Users/.../sw.js:2:76) at Module._compile (module.js:460:26) at Object.Module._extensions..js (module.js:478:10) at Module.load (module.js:355:32) at Function.Module._load (module.js:310:12) at Function.Module.runMain (module.js:501:10) at startup (node.js:129:16) at node.js:814:3 

节点版本(不确定是否相关)

 node -v v0.12.8 

您的节点版本不支持ecmascript6function,例如String.prototype.startsWith() 。 在编写本文时,Node的最新版本是6.9.2 / 7.3.0,因此您应该考虑将节点升级到最新版本,因为您的版本已经很老了。

但是,如果你不可能,你可以使用mdn上的polyfill :

 if (!String.prototype.startsWith) { String.prototype.startsWith = function(searchString, position) { position = position || 0; return this.indexOf(searchString, position) === position; }; } 

startsWith仅在es6中可用,而您的节点版本不支持。 尝试升级您的节点到节点v6(当前LTS),它应该工作。