我想動態生成一個整數(在下面的情況下,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 – jbabey
可讀性是我最好的朋友!並感謝+1! – gonzofish
謝謝,真棒!我一直在試圖圍繞如何使用json創建它,但我對js和所有這些都很陌生,所以我需要學習更多東西。你會非常好,並解釋爲什麼我的初始代碼失敗?或者它能以某種方式工作?實際上,它確實如此,但它只能顯示「message1」而不是2和3 ... – phillyooo