Reputation: 19
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?
Upvotes: 0
Views: 96
Reputation: 3848
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
}
}
Upvotes: 0
Reputation: 44581
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
}
}
Upvotes: 1