2012-10-15 37 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;