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

旧巷老猫 提交于 2020-01-21 14:08:14

问题


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. On the first level I want to create a closure that has its own data. Why is stepFunc[1] "undefined" ?


回答1:


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


来源:https://stackoverflow.com/questions/4200873/why-is-this-function-returning-undefined-instead-of-the-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!