動的に整数 (以下の場合は 100 または 500) を生成し、それを使用して別の配列にアクセスしたいと思います。後のステップ (以下のコードの一部ではありません) で、これらの配列のさまざまな部分にも同じ方法でアクセスしたいと思います (「メッセージ 1、2、または 3」)。
この概念実証では、整数を動的に生成しませんでしたが、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);