Java script code check

Can some one tell me if my variable “mr” should be compared to a string or a number? I am using math.floor(math.random) formula. Also should I be using else if, instead of just if.

Thanks


var curcontentindex=0
var messages=new Array()
function getElementByClass(classname){
 var inc=0
 var alltags=document.all? document.all : document.getElementsByTagName("*")
 for (i=0; i<alltags.length; i++){
  if (alltags*.className==classname)
  messages[inc++]=alltags*
 }
}
function rotatecontent(){
 //get current message index (to show it):
 curcontentindex=0;    
 //set random to display groups of pics
 var mr = Math.floor(Math.random()*4);  
 if (mr=="0"){
  curcontentindex=0;
  //alert("currentindex=0");
  prevcontentindex=0;
 }
  if(mr=="1"){
  curcontentindex=1;
  //alert("currentindex=1");
  prevcontentindex=0;
 }
  if(mr=="2"){
  curcontentindex=2; 
  //alert("currentindex=2");
  prevcontentindex=1;
 }
 if(mr=="3"){
  curcontentindex=3; 
  //alert("currentindex=3");
  prevcontentindex=2;
 }    
 messages[prevcontentindex].style.display="none" //hide previous message
 messages[curcontentindex].style.display="block" //show current message
}

I’m pretty sure it should be an integer (number).

The floor() method returns an Integer, yes.


if(mr == 0) {

} else if(mr == 1) {

} else if(mr == 2) {

} else if(mr == 3) {

}

is more efficient than


if(mr == 0) {

}

if(mr == 1) {

}

if(mr == 2) {

}

if(mr == 3) {

}

However, this is dependent on the value of mr. If mr is 0, then the first example above will stop after the first ‘if’ statement. In other words, if the first if statement results to true, then none of the ‘else if’ statements afterwards can possibly be true so the interpreter doesn’t even bother to evaluate them.

In the second example (your code) it evaluates every if statement regardless of whether or not the value of mr has already been determined. Thus, if mr is 0 then the first code block is roughly four times more efficient. If mr is 3 then there is no difference.

Hope this helps…

jwilliam is correct! You should use "else if" UNLESS you are doing something like this:


if ( mr == 1 )
{
mr = 2;
//other code...
}
if ( mr == 2 )
{
//some other code...
}

Unusual, but it depends on your application. And here you NEED multiple if statements, and not else-if statements.
Also, just in case you didn’t know, such questions go in the Client-Side sub-forum we have, because Java and JavaScript are different. :slight_smile: