简体   繁体   English

为什么此函数返回“未定义”而不是数组?

[英]Why is this function returning “undefined” instead of the array?

This work: 这项工作:

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
];

This does NOT work : 这不起作用:

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;
            }
        ];      
    })(), 
    // ...
];

I would like that stepFunc would be an array of arrays of functions. 我希望stepFunc将是一组函数数组。 On the first level I want to create a closure that has its own data. 在第一层,我想创建一个具有自己数据的闭包。 Why is stepFunc[1] "undefined" ? 为什么stepFunc [1]是“ undefined”?

You're probably stumbling over implicit statement termination, aka implicit semicolon insertion. 您可能在隐式语句终止(又名隐式分号插入)上遇到了麻烦。 The line after return is ignored completely and nothing is returned. return之后的行将被完全忽略,并且不返回任何内容。 This works: 这有效:

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;
                  }
               ];         
           })()
];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM