0

I have 2 arrays :

A1=[num1,num2,num3]

B1=[digit1,digit2,digit3]

I want to create a function that :

gets digit1, digit2 and digit3 and compares them with A1 elements and do the following:

if(digit1>num1)
//draw next page

else if(digit1<num1)
//go to previous page

else if(digit1==num1)
//go and check "digit2" with "num2"

if(digit2>num2)
//draw next frame

else if(digit2<num2)
//remove the latest frame added

else if(digit2==num2)
//got check "digit3" with "num3"

if(digit3>num3)
//draw a div

else if(digit3<num3)
//remove the previous div added

else if(digit3==num3)
//some statement

Is there any way I can avoid all this "if-else" and implement this using perhaps a for loop?

3
  • What is //some statement? The same everywhere? Commented Jun 14, 2014 at 14:00
  • Are those statements all different? Commented Jun 14, 2014 at 14:00
  • I don't see any reason for a loop if those statements are all different and do not follow a certain scheme. Or can you generalize them? Commented Jun 14, 2014 at 14:07

2 Answers 2

1
if( A1.length == B1.length ) {
   for(var i = 0; i < A1.length ; i++) {
     if( A1[i] > B1[i] )
       //some statement
     else if( A1[i] < B1[i] )
       //some statement
     else if( A1[i] == B1[i] )
       //some statement
   }
}
Sign up to request clarification or add additional context in comments.

1 Comment

for..in loops are a bad way of iterating arrays.
0

While @Notulysses answer is already a good start, you could enhance your logic like this:

var dialogs = [  // an indexed Array of the dialogs

    {  // first dialog
        num: 0,
        digit: 0,
        greaterFun: function () {
            // statement if greater than
        },
        lowerFun: function () {
            // statement if lower than
        },
        equalityFun: function () {
            // statement when this.num === this.digit
        }
    }

    /*, {  // second dialog
        num: 1,
        digit: 1,
        greaterFun: function () {
            // statement if greater than
        },
        lowerFun: function () {
            // statement if lower than
        },
        equalityFun: function () {
            // statement when this.num === this.digit
        }
    } */

];

Usage

for (var i = 0; i < dialogs.length; i++) {
    var dialog = dialogs[i];

    if (dialog.digit > dialog.num) {
        dialog.greaterFun();
    }
    else if (dialog.digit < dialog.num) {
        dialog.lowerFun();
    }
    else if (dialog.digit === dialog.num) {
        dialog.equalityFun();
    }
    else {
        // handle an error
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.