我有以下IF条件代码:
if ((depth <= min_depth ) && (leaf_colour == "red")){
for (i = 0; i < array_2D.length; i++) {
var leaf_size = array_2D[i][1];
if (leaf_size == 10 || leaf_size == 11){
alert("Error message.");
break; // we found an error, displayed error message and now leave the loop
}
else{ go to the next else section }
}
}//end of if condition
else{
...
...
...
...
...
}
在'FOR'循环中,如果(leaf_size == 10 || leaf_size == 11),我们打破循环并且什么也不做,但如果不是这样,我想在下一个ELSE中运行代码部分。
我不想复制整个代码块并将其粘贴到for循环的'else'部分,因为它很长。
有没有办法在第二个其他部分运行代码?
答案 0 :(得分:2)
您需要将第二个else
块中的代码移动到单独的函数中。然后,您可以在需要运行该代码的任何位置调用该函数:
function newFunction() {
//Shared code. This is executed whenever newFunction is called
}
if(someCondition) {
if(someOtherCondition) {
//Do stuff
}
else {
newFunction();
}
}
else {
newFunction();
}
答案 1 :(得分:1)
var ok = (depth <= min_depth ) && (leaf_colour == "red");
if (ok){
for (i = 0; i < array_2D.length; i++) {
var leaf_size = array_2D[i][1];
if (leaf_size == 10 || leaf_size == 11){
alert("Error message.");
ok = false;
break;
}
else{
ok = true;
break;
}
}
}//end of if condition
if(!ok) {
...
...
...
...
...
}