描述:
我正在使用这个功能。这个想法是用一个自执行函数启动一个列表,然后在自执行函数中调用那个自执行函数。
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 : 谢谢 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/