Javascript“预设”变量?

时间:2012-05-17 19:48:02

标签: javascript jquery variables

我正在尝试声明一个变量,其值是另一个当时未设置的变量。

var add = 1 + three;
var three = 3;
document.getElementById('thediv').innerHTML = add;
//results in "NaN"

http://jsfiddle.net/seSMx/1/

有没有办法使用Jquery / Javascript?

2 个答案:

答案 0 :(得分:11)

您可以将添加功能转换为

http://jsfiddle.net/seSMx/3/

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);