我正在尝试声明一个变量,其值是另一个当时未设置的变量。
var add = 1 + three;
var three = 3;
document.getElementById('thediv').innerHTML = add;
//results in "NaN"
有没有办法使用Jquery / Javascript?
答案 0 :(得分:11)
您可以将添加功能转换为
function add() {
return 1 + (three || 0);
}
var three = 3;
document.getElementById('thediv').innerHTML = add();
虽然,在我看来这很难遵循。我会更进一步,让three
成为add
function add(three) {
return 1 + (three || 0);
}
document.getElementById('thediv').innerHTML = add(3);
答案 1 :(得分:6)
这就是你想要的吗?
var add = "1 + three";
var three = 3;
document.getElementById('thediv').innerHTML = eval(add);