omega_lonestar
10-14-2008, 03:56 PM
I have a quick question. I'm writing a piece of code that will generate if it is an odd number or an even number. I was able to get the output. Now I'm trying to figure out how can I declare the function twice. This is my code:
function f(n)
{
document.write(n);
}
var m=Math.round(1+ Math.random()*100);
if (m%2!==0)
f(m + " is an odd number<br>");
else
f(m + " is an even number<br>");
Philip M
10-14-2008, 05:37 PM
No, you cannot have multiple scripts with the same names of functions and/or variables.
If you require a second instance of the same script you must rename all functions and variables to (say) m2 and so on.
Your code has several errors:
var m = Math.round(1+ Math.random()*100);
if (m%2 != 0) {
var f = (m + " is an\nodd number");
}
else {
f = (m + " is an\neven number");
}
alert (f)
Not equal to is != not !==
Newline is \n not <br> which is a literal, but newline is not required here.
If at first you don't succeed, redefine success.
rnd me
10-14-2008, 07:06 PM
Not equal to is != not !==
Newline is \n not <br> which is a literal, but newline is not required here.
actually not equal is !==, not equivalent is !=.
although all it really needs is the condition changed to if(m%2). no reason to compare to zero here...
OP:
not sure what you mean by "declare the function twice".
you could wrap your loose code in a function, at which point it can be called repeatedly:
function f(n){document.write(n);}
function reportEveness(m){
if (m%2){
f(m + " is an odd number<br>");
}else{
f(m + " is an even number<br>");
}
}
// do two different numbers:
var n=Math.round(1+ Math.random()*100);
reportEveness(n);
n=Math.round(1+ Math.random()*100);
reportEveness(n);
omega_lonestar
10-16-2008, 01:32 PM
Thank you kindly :) I was able to figure out the coding. I meant to say that I would like to run the function twice so that way the results from the random function appears differently rather than the same.