开发者

Why is this function returning "undefined" instead of the array?

开发者 https://www.devze.com 2023-01-25 05:27 出处:网络
This work: var stepFunc = [ //Step 0 (it doe not exist) function(){console.log(\"Step 0\");}, //Step 1 (function(){

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 =
[ // St开发者_C百科ep 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. On the first level I want to create a closure that has its own data. Why is stepFunc[1] "undefined" ?


You're probably stumbling over implicit statement termination, a.k.a. implicit semicolon insertion. The line after return is ignored completely and nothing is returned. 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;
                  }
               ];         
           })()
];
0

精彩评论

暂无评论...
验证码 换一张
取 消