Javascript "pre set" variable?

I am trying to declare a variable whose value is another variable that is not set at this time.

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

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

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

+6
source share
2 answers

You can enable the add function,

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

 function add() { return 1 + (three || 0); } var three = 3; document.getElementById('thediv').innerHTML = add(); 

Although, in my opinion, it will be very difficult. I would take it a step further and make the three add argument

 function add(three) { return 1 + (three || 0); } document.getElementById('thediv').innerHTML = add(3); 
+11
source

what are you gonna do

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

Source: https://habr.com/ru/post/916029/


All Articles