javascript - 为什么这个函数返回 "undefined"而不是数组?

标签 javascript arrays multidimensional-array

这项工作:

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/

相关文章:

javascript - 如何阅读代码中的函数描述?

javascript - 如何减去对象数组中具有相似键的对象值? (不要与删除重复项混淆)

java - 如何用 Jackson 解析嵌套数组?

javascript - 将嵌套数组转换为对象

javascript - 用鼠标悬停打开/关闭导航,在移动设备上触摸?

javascript - 使用 $filter 根据 Angular Controller 中的属性对对象数组进行排序

java - 使用变量初始化整数数组

c++ - 多维锯齿状图

javascript - 如何垂直和水平对齐一个div到页面中心

python - 洪水填充 NumPy 数组 `numpy.ndarray` ,i。 e.为元素分配新值并更改相同值的相邻元素