javascript - 使用数组和自执行函数创建循环

标签 javascript

描述:

我正在使用这个功能。这个想法是用一个自执行函数启动一个列表,然后在自执行函数中调用那个自执行函数。

var arr = [(function(){

    //when first entering here arr is currently undefined

    //here I call an asynchronous function that will start in 1 second
    setTimeout(function(){
        //1 second has passed so arr has been initiated.
        //Notice that arr[Ø] is undefined and arr[1] isn't
        //Why?
        console.log('Why is this: ' + arr[0] + ' and ' + arr[1] + ' isnt ');
    }, 1000);

})(), 2];

所以最后我尝试创建一个循环。

问题:

在自执行函数中,我创建了一个 setTimeout 并等待 1 秒让我的 arr 完成自身启动。为什么 arr[0] 未定义而 arr[1] 不是?甚至可以通过这种方式创建循环吗?

DEMO

最后的工作 demo : 谢谢 NoDownVotesPlz

最佳答案

arr[0] 未定义,因为该函数在您的函数中不返回任何内容,

如果你想显示一些值,你应该在 setTimeout 之后从函数返回它:DEMO

var arr = [(function() {



  setTimeout(function() {

    document.write('Why is this: ' + arr[0] + ' and ' + arr[1] + ' isnt ');

  }, 1000);

  return 1 // return here
})(), 2];

关于javascript - 使用数组和自执行函数创建循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29075412/

相关文章:

javascript - jQuery 父级();函数 removeClass();不工作(错误)

javascript - Angular.js - 在其他任何事情之前运行服务功能?

javascript - 在应用 substr() 之前检查 .length 吗?

javascript - 为什么没有定义 AbortController?

javascript - 类型错误 : Cannot read property 'rtl' of undefined

javascript如何计算多行动态添加字段中的值

javascript - 将 html 添加到 switch 语句中

javascript - 类列表切换不会为 div 添加/切换类名

javascript - 在 d3 Canvas map 上绘制圆弧时出现问题

javascript - LoDash _.has 用于多个键