我正在尝试将一个随机数附加到字符串中,然后将其解析为我的innerHTML中的变量名。
var a = Math.floor((Math.random() * 3) + 1);
var description1 = "This is description 1";
var description2 = "This is description 2";
var description3 = "This is description 3";
var desc = "description" + a;
var div = document.getElementById('result');
div.innerHTML += desc;
我得到了回复,例如“description1”,但没有“这是描述1”。怎么会遇到这个?
答案 0 :(得分:1)
您不能将interger附加到这样的变量名称。相反,你应该使用数组来实现这一目标。
var a = Math.floor((Math.random() * 3));
var description = Array(3);
description[0] = "This is description 1";
description[1] = "This is description 2";
description[2] = "This is description 3";
var desc = description[a];
var div = document.getElementById('result');
div.innerHTML += desc;
<div id="result"></div>
答案 1 :(得分:0)
您可以使用括号表示法按名称引用变量...
var a = Math.floor((Math.random() * 3) + 1);
var description1 = "This is description 1";
var description2 = "This is description 2";
var description3 = "This is description 3";
var desc = "description" + a;
var div = document.getElementById('result');
div.innerHTML += window[desc];
<div id="result"></div>
但是,这需要使用全局窗口范围,这不是一个好主意。它会污染所有脚本使用的窗口对象。你可以简单地创建一个数组(根据void的另一个答案),或者创建一个对象并使用它而不是window
......
var a = Math.floor((Math.random() * 3) + 1);
var descriptions = {
description1: "This is description 1",
description2: "This is description 2",
description3: "This is description 3"
};
var desc = "description" + a;
var div = document.getElementById('result');
div.innerHTML += descriptions[desc];
<div id="result"></div>