这项工作:
var stepFunc =
[
//Step 0 (it doe not exist)
function(){console.log("Step 0");},
//Step 1
(function(){
var fFirstTime = true;
return function(){
console.log("Step 1");
if (fFirstTime){
//Do Something
}
}
})(),
// ... Other steps
];
这不起作用:
var stepFunc =
[ // Step 0
[
function(){console.log("Step 0");},
function(){console.log("Check Step 0");}
], //Step 1
(function(){
var fFirstTime = true;
return
[
function() { //Initialization function
console.log("Step 1");
if (fFirstTime){
//Do somrthing
}
}, function() {
return true;
}
];
})(),
// ...
];
我希望 stepFunc 是一个函数数组的数组。在第一个级别上,我想创建一个拥有自己的数据的闭包。为什么stepFunc[1]“未定义”?
最佳答案
您可能会被隐式语句终止(也称为隐式分号插入)绊倒。 return
之后的行将被完全忽略,并且不会返回任何内容。这有效:
var stepFunc = [
// Step 0
[
function(){console.log("Step 0");},
function(){console.log("Check Step 0");}
], //Step 1
(function(){
var fFirstTime = true;
return [ // <-- important to begin the return value here
function() {
console.log("Step 1");
if (fFirstTime){
//Do somrthing
}
}, function() {
return true;
}
];
})()
];
关于javascript - 为什么这个函数返回 "undefined"而不是数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4200873/