2016-09-20 30 views
-2

试图通过i进入封闭来使它局部避免i关闭问题基本维持在2为什么我不能传递的参数在起作用for循环

var myFunctions = {}; 

for (var i = 0; i < 3; i++) {  // let's create 3 functions 

    myFunctions[i] = function(i) { // and store them in myFunctions 
     console.log("My value: " + i); // each should log its value. 
    }; 

} 

for (var j = 0; j < 3; j++) { 
    myFunctions[j]();    // and now let's run each one to see 
} 

// > "My value: undefined 
// > "My value: undefined 
// > "My value: undefined 
+3

那么当你调用函数,你** **不传递参数。 – Pointy

+0

我是一个白痴:) – js2015

+1

调用它像'myFunctions [j](j);' – Redu

回答

1

这是发生的原因是因为你有i中的功能参数,但你不及格的值。

有三种方法可以解决这个问题。


首先,你可以通过值作为函数参数:

myFunctions[j](j); 

第二种方法是使用函数闭包存储值:

var myFunctions = {} 

function generateValuePrintout (value) { 
    return function() { 
     console.log("My value: " + value); 
    }; 
} 

for (var i = 0; i < 3; i++) { 
    myFunctions[i] = generateValuePrintout(i); 
} 

for (var j = 0; j < 3; j++) { 
    myFunctions[j](); 
} 

这是比第一种方法更简单的方法,因为这意味着您不需要将任何值传递给函数以便知道它的c losure。


最后一个办法(我的最爱)。将存储使用let(因此它被正确作用域)函数的值,然后调用它没有一个参数(由函数定义也删除参数):

for (var i = 0; i < 3; i++) {  // let's create 3 functions 

    let closureValue = i; 

    myFunctions[i] = function() { // and store them in myFunctions 
     console.log("My value: " + closureValue); // each should log its value. 
    }; 

} 
for (var j = 0; j < 3; j++) { 
    myFunctions[j]();    // and now let's run each one to see 
} 

每个的输出将是:

我的值:0

我的价值:1个

我值:2

1

要调用该函数不需要传递它所需要的参数。

var myFunctions = {}; 

for (var i = 0; i < 3; i++) { 
    myFunctions[i] = function (i) { 
     console.log("My value: " + i); 
    }; 
} 

for (var j = 0; j < 3; j++) { 
    myFunctions[j](j); // Passing the required parameter 
} 

// > "My value: 0 
// > "My value: 1 
// > "My value: 2 
+0

对不起。我认为这很清楚。我附上了固定代码。 – felipeptcho

2

这是因为在函数定义的i的期望是什么作为参数传递给函数

试试这个

var myFunctions = {}; 

for (var i = 0; i < 3; i++) {  // let's create 3 functions 

    myFunctions[i] = function(i) { // and store them in myFunctions 
     console.log("My value: " + i); // each should log its value. 
    }; 

} 
for (var j = 0; j < 3; j++) { 
    myFunctions[j](j);    // pass j as parameter 
} 
0

虽然参数不是necessarry在JavaScript

但如果你想要使用的值应该在那里参数

for (var j = 0; j < 3; j++) { 
myFunctions[j]("name"+j);    // and now let's run each one to see 
} 

输出

My value: name0 

My value: name1 

My value: name2 
相关问题