Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/410.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在内联函数中访问此变量?_Javascript_Copy_Inline Functions - Fatal编程技术网

Javascript 如何在内联函数中访问此变量?

Javascript 如何在内联函数中访问此变量?,javascript,copy,inline-functions,Javascript,Copy,Inline Functions,这是我的困境 我有这段代码: var list_of_numbers = new Array(); function AddToArray(func) { // Add to the *beginning* of the array // essentially reversing the order list_of_numbers.unshift(func); } function DisplayNumber(num) { document.write(n

这是我的困境

我有这段代码:

var list_of_numbers = new Array();

function AddToArray(func)
{
    // Add to the *beginning* of the array
    // essentially reversing the order

    list_of_numbers.unshift(func);
}

function DisplayNumber(num)
{
    document.write(num);
}

for(var i=0;i<5;++i)
{
   AddToArray(function() { DisplayNumber(i); });
}

for(var i=0;i<5;++i)
{
   list_of_numbers[i]();
}​
var list_of_numbers=新数组();
函数AddToArray(func)
{
//添加到数组的*开头*
//基本上颠倒了顺序
编号列表。取消移位(func);
}
函数DisplayNumber(num)
{
文件写入(num);
}

对于(var i=0;i您有两个独立的问题,都与范围相关

var list_of_numbers = new Array(); 
function AddToArray(func) 
{ 
    // Add to the *beginning* of the array
    // essentially reversing the order 
    list_of_numbers.unshift(func); 
} 

function DisplayNumber(num) 
{ 
    document.write(num); 
} 
for(var i=0;i<5;++i) 
{ 
    (function(i) 
     { 
         AddToArray(function(){ DisplayNumber(i); });
     })(i); 
} 

for(var j=0;j<5;++j) 
{ 
    list_of_numbers[j](); 
}​
var list_of_numbers=新数组();
函数AddToArray(func)
{ 
//添加到数组的*开头*
//基本上颠倒了顺序
编号列表。取消移位(func);
} 
函数DisplayNumber(num)
{ 
文件写入(num);
} 

对于(var i=0;i@Michael:我不明白你在说什么。@Michael:我知道-这就是它应该做的。问题是它没有在循环的每次迭代中保存
I
的值……我想。是的,JavaScript没有“保存”值。你有.ahhh。我明白了。
AddToArray
块的语法非常奇怪!那谢谢你的帮助。