2012-10-15 38 views
1

我想動態生成一個整數(在下面的情況下,100或500),並使用它來訪問單獨的數組。在後面的步驟中(不是下面的代碼的一部分),我還想以相同的方式訪問這些數組的不同部分(「消息1,2或3」)。動態javascript變量

對於這個概念證明我沒有動態生成一個整數的,但我只是將它設置爲100

然後我試圖用eval()動態生成由「警告」和100的數組名,但它工作不正常。

這是我的代碼:

// two arrays are defined, warning100 and warning500 
var warning100 = [ 
    { "message1":"Ok, go ahead and start typing!" }, 
    { "message2":"Keep going!" }, 
    { "message3":"You can do it!" } 
]; 

var warning500 = [ 
    { "message1":"Slow down..." }, 
    { "message2":"That's it!" }, 
    { "message3":"Maximum reached." } 
]; 

// set i to 100 and h to 1 for testing purposes, will be random integers in the final version 
var i = 100; 
var h = 2; 
// create variable names as a combination of a string and i or h 
// those variables will be used to access one of the arrays from above and one of the messages; 
eval("var warningNumber = warning" + i + ";"); 
eval("var messageNumber = message" + h + ";"); 

/* alternative code for creating the two variable values 
var warningNumber = "warning" + i; 
var messageNumber = "message" + h; 
*/ 

// the variable warningNumber from above is now used again to access the array warning100 
// the varaible messageNumber is used to access one of the messages 
// within that array message1 should be displayed 
// create variable to be used in the document.write below 
var warning = warningNumber[0].messageNumber; 

// should alert "Ok, go ahead and start typing!"  
alert(warning); 

回答

1

爲什麼不乾脆讓每個集warningNumber對象的警告部分?這樣,你可以做

var warnings = {100: { 1:"Ok, go ahead and start typing!", 
         2:"Keep going!", 
         3:"You can do it!" 
        }, 
       500: { 1:"Slow down...", 
         2:"That's it!", 
         3:"Maximum reached." 
        } 
       }; 
alert(warnings[i][h]); 

這樣,所有的eval甚至不必做。

+1

,這是最好的答案。 +1 – jbabey

+0

可讀性是我最好的朋友!並感謝+1! – gonzofish

+0

謝謝,真棒!我一直在試圖圍繞如何使用json創建它,但我對js和所有這些都很陌生,所以我需要學習更多東西。你會非常好,並解釋爲什麼我的初始代碼失敗?或者它能以某種方式工作?實際上,它確實如此,但它只能顯示「message1」而不是2和3 ... – phillyooo

-1

試試這個:

var warnings = { 

    warning100: { 
     "message1":"Ok, go ahead and start typing!", 
     "message2":"Keep going!", 
     "message3":"You can do it!" 
    }, 
    warning500: { 
     "message1":"Slow down...", 
     "message2":"That's it!", 
     "message3":"Maximum reached." 
    } 
} 

var i = 100; 
console.log(warnings["warning" + i]); 
i += 400; 
console.log(warnings["warning" + i]); 

console.log(warnings["warning" + i ]["message1"]); 

Example

+0

好的,謝謝,但我是一個javascript新手,對不起:/我需要訪問數組和單獨的「消息」。你的代碼將作爲輸出提供什麼?如果我將console.log更改爲警報,它將不會執行任何操作... – phillyooo

+0

我更新了它:)您可以獲取消息對象或單個消息。 – EricG

+0

@EricG downvoting每個競爭的答案? – Christoph

0

爲什麼不把它包裝在一個對象中?

var dynamicHolder = {}; 
var i = 100; 
var h = 2; 
dynamicHolder["warningNumber"] = "warning" + i; 
dynamicHolder["messageNumber"] = "message" + h;