我有2个阵列:
A1=[num1,num2,num3]
B1=[digit1,digit2,digit3]
我想创建一个函数:
获取digit1
,digit2
和digit3
并将其与A1 elements
进行比较,然后执行以下操作:
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
有什么方法可以避免所有这些“if-else”并使用for循环来实现这个?
答案 0 :(得分: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
}
}
答案 1 :(得分:0)
虽然@Notulysses答案已经是一个好的开始,但你可以像这样增强你的逻辑:
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
}
} */
];
用法
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
}
}