2011-07-11 74 views
35

動態創建變量如何使用一個for循環動態創建變量,並返回。的JavaScript:for循環

function createVariables() 
{ 
for (i=0; i<=20; i++) 
    { 
     var account = i; 
     return var account + i; 
    } 
} 

的目標是讓下面的結果:

var account1; 
var account2; 
var account3; and etc..... 

回答

78

您應該使用數組:

function createVariables(){ 
    var accounts = []; 

    for (var i = 0; i <= 20; ++i) { 
     accounts[i] = "whatever"; 
    } 

    return accounts; 
} 

然後通過accounts[20]訪問accounts[0]

0
function createVariables() { 
    var accounts = []; 
    for (var i = 0; i <= 20; ++i) { 
     accounts[i] = "merhaba" + i; 
     } 
     return accounts; 
} 
+1

這將有助於你的代碼一起添加的解釋說明,讓OP和其他人能更好地理解它。 – Charles