The forums have permanently moved to This forum will be kept around in read-only mode for archival purposes. To learn how to continue using your existing account on the new forums, check out this thread.

Results 1 to 4 of 4

Thread: java script code check

  1. #1

    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.


    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[i].className==classname)
    function rotatecontent(){
     //get current message index (to show it):
     //set random to display groups of pics
     var mr = Math.floor(Math.random()*4);  
     if (mr=="0"){
     messages[prevcontentindex].style.display="none" //hide previous message
     messages[curcontentindex].style.display="block" //show current message

  2. #2
    I'm pretty sure it should be an integer (number).

  3. #3
    jwilliam's Avatar
    An intellectual carrot!
    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...

  4. #4
    jwilliam is correct! You should use &quot;else if&quot; 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.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Home About Meet the Moderators Advertise

 Link to Us


Copyright 1999 - 2012