var arr2 = ["WEST","NORTH"];
var num1 = 0;
function checkDir(arr,num){
if (num == arr.length-1 || arr == '' || arr == ["NORTH","WEST","SOUTH","EAST"]) {
alert(arr);
return arr;
}else{
alert("走了這裡");
switch(arr[num]){
case "NORTH":
alert(1);
dirCompare("SOUTH",num,arr);
break;
case "SOUTH":
alert(2);
dirCompare("NORTH",num,arr);
break;
case "EAST":
alert(3);
dirCompare("WEST",num,arr);
break;
case "WEST":
alert(4);
dirCompare("EAST",num,arr);
break;
}
}
}
function dirCompare(str,num,arr1){
var switch1 = 0;
for (var i = num+1; i < arr1.length; i++) {
if (arr1[i]==str){
arr1.splice(num,1);
arr1.splice(i-1,1);
switch1 = 1;
checkDir(arr1,num);
return;
}
};
if (switch1 == 0){
num++;
alert(arr1 + "-" + num);
checkDir(arr1,num);
}
}
alert(checkDir(arr2,num1));
這是一個判斷方向的需求,每一對東西或南北都被剔除,上面函數裡直接判斷無法消除的兩個方向,一直到第一個if條件中的alert都能正確返回需要的結果,但是後面的return arr似乎就沒有被執行,最後函數返回值也是undefined,求大神解惑這是哪地方寫錯了。
var arr2 = ["WEST", "NORTH"];
var num1 = 0;
function checkDir(arr, num) {
if (num == arr.length - 1 || arr == '' || arr.join() == ["NORTH", "WEST", "SOUTH", "EAST"]) {
alert(arr);
alert('return')
return arr;
} else {
alert("走了這裡");
switch (arr[num]) {
case "NORTH":
alert(1);
return dirCompare("SOUTH", num, arr);/////////要return返回值
break;
case "SOUTH":
alert(2);
return dirCompare("NORTH", num, arr);/////////要return返回值
break;
case "EAST":
alert(3);
return dirCompare("WEST", num, arr);/////////要return返回值
break;
case "WEST":
alert(4);
return dirCompare("EAST", num, arr);/////////要return返回值
break;
}
}
}
function dirCompare(str, num, arr1) {
var switch1 = 0;
for (var i = num + 1; i < arr1.length; i++) {
if (arr1[i] == str) {
arr1.splice(num, 1);
arr1.splice(i - 1, 1);
switch1 = 1;
return checkDir(arr1, num);/////////要return返回值
//return;
}
};
if (switch1 == 0) {
num++;
alert(arr1 + "-" + num);
return checkDir(arr1, num);/////////要return返回值
}
}
alert(checkDir(arr2, num1));
除非第一次執行checkDir成功才會執行return,else分支你的其他函數要增加return