尝试执行以下自定义任务:
'use strict';
module.exports = function(grunt) {
grunt.initConfig({
log: {
one: [1, 2, 3],
two: "Hello World",
three: true,
four: {
five: function() {
grunt.log.writeln("Hi");
},
six: function() {
grunt.log.writeln("Welcome");
}
}
}
});
grunt.registerMultiTask('log', 'Log stuff', function() {
grunt.log.writeln(this.target + ": " + this.data + "\n");
if (this.target === 'four') {
console.log(this.data);
for(var d in this.data) {
console.log(this.data['five']());
console.log(this.data['six']());
}
}
});
grunt.registerTask('default', 'log');
};
我的输出低于输出:
Running "log:one" (log) task
one: 1,2,3
Running "log:two" (log) task
two: Hello World
Running "log:three" (log) task
three: true
Running "log:four" (log) task
four: [object Object]
{ five: [Function], six: [Function] }
Hi
undefined
Welcome
undefined
Hi
undefined
Welcome
undefined
Done, without errors.
执行第五和第六功能时我无法理解;它用" undefined"显示正确的输出。从哪里来的未定义?
答案 0 :(得分:1)
当你写console.log(this.data['five']());
时,它意味着“打印出this.data.five
定义的函数的返回值,即:
function() {
grunt.log.writeln("Hi");
}
此函数没有明确的return
,因此其返回值为undefined
,您的代码将其打印出来。
要避免这种情况,请将代码更改为:
for(var d in this.data) {
this.data['five']();
this.data['six']();
}
甚至更好,避免重复:
for(var d in this.data) {
this.data[d]();
}