admin管理员组

文章数量:1417434

I'm trying to declare a variable whose value is another variable that isn't set at that time.

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

/

Is there a way to do this using Jquery/Javascript?

I'm trying to declare a variable whose value is another variable that isn't set at that time.

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

http://jsfiddle/seSMx/1/

Is there a way to do this using Jquery/Javascript?

Share Improve this question asked May 17, 2012 at 19:48 NorseNorse 5,75716 gold badges53 silver badges86 bronze badges 5
  • 4 Why would you want to do that? – Alexis Pigeon Commented May 17, 2012 at 19:49
  • 2 Why not var three = 3; var add = 1 + three;? >> jsfiddle/skram/seSMx/2 << – Selvakumar Arumugam Commented May 17, 2012 at 19:50
  • If I told you, would you have an answer? – Norse Commented May 17, 2012 at 19:50
  • 7 It may suggest an alternative solution if you explained what you're doing (and why). – David Thomas Commented May 17, 2012 at 19:51
  • @Dasarp You might want to put that as an answer, instead of a ment; you don't get rep for ments. – Daedalus Commented May 17, 2012 at 19:54
Add a ment  | 

2 Answers 2

Reset to default 11

You could turn add into a function,

http://jsfiddle/seSMx/3/

function add() {
   return 1 + (three || 0);
}

var three = 3;
document.getElementById('thediv').innerHTML = add();

Although, this would be very hard to follow in my opinion. I would take it a step farther and make three an argument to add

function add(three) {
   return 1 + (three || 0);
}

document.getElementById('thediv').innerHTML = add(3);

is this what are you going for?

var add = "1 + three";
var three = 3;
document.getElementById('thediv').innerHTML = eval(add);

本文标签: jqueryJavascript quotpre setquot a variableStack Overflow