在 grunt 任务中使用自定义函数执行变得不确定
Getting undefined with custom function execution in grunt task
尝试执行以下自定义任务:
'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" 的正确输出。这个 undefined 是从哪里来的?
当你写 console.log(this.data['five']());
时,它的意思是“打印出在 this.data.five
处定义的函数的 return 值,即:
function() {
grunt.log.writeln("Hi");
}
这个函数没有明确的return
,所以它的return值是undefined
,你的代码打印出来了。
为避免这种情况,请将您的代码更改为:
for(var d in this.data) {
this.data['five']();
this.data['six']();
}
或者更好的是,避免重复:
for(var d in this.data) {
this.data[d]();
}
尝试执行以下自定义任务:
'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" 的正确输出。这个 undefined 是从哪里来的?
当你写 console.log(this.data['five']());
时,它的意思是“打印出在 this.data.five
处定义的函数的 return 值,即:
function() {
grunt.log.writeln("Hi");
}
这个函数没有明确的return
,所以它的return值是undefined
,你的代码打印出来了。
为避免这种情况,请将您的代码更改为:
for(var d in this.data) {
this.data['five']();
this.data['six']();
}
或者更好的是,避免重复:
for(var d in this.data) {
this.data[d]();
}