自定义 grunt 任务错误 "Object has no method 'endsWith'"

Error "Object has no method 'endsWith'" on custom grunt task

我 运行 在自定义 grunt 任务中出错。下面我发布了一个与问题相关的简单测试用例:

Gruntfile.js

module.exports = function( grunt ){

    grunt.task.registerTask( 'endsWith', 'Test of string.prototype.endsWith', function(){
        var value = grunt.option('value');
        grunt.log.writeln( typeof value );
        grunt.log.writeln( value.endsWith( 'bar' ) );
    })

};

测试

> grunt endsWith --value=foobar
Running "endsWith" task
string
Warning: Object foobar has no method 'endsWith' Use --force to continue.

Aborted due to warnings.

Execution Time (2016-02-12 16:15:19 UTC)
Total 12ms

好像 grunt 不识别 String.proptotype.endsWith 函数。这正常吗?

编辑:我正在使用节点 v0.10.4

.endsWith is an ES6 feature 并且未在 Node.js v0.10.4 中实现。

要使用 .endsWith,请升级 Node.js 或 add in a polyfill

String.prototype.endsWith = function(suffix) {
    return this.indexOf(suffix, this.length - suffix.length) !== -1;
};

如果您使用的是旧版本的节点,您可以使用 String.match 方法。

替换

grunt.log.writeln(value.endsWith('bar'));

grunt.log.writeln( value.match("bar$") );

完整代码

module.exports = function( grunt ){

    grunt.task.registerTask( 'endsWith', 'Test of string.prototype.endsWith', function(){
        var value = grunt.option('value');
        grunt.log.writeln( typeof value );
        grunt.log.writeln( value.match("bar$") );
    })

};