简体   繁体   English

为什么函数返回 undefined?

[英]Why does a function return undefined?

I have an array, each value of which means a side of the world:我有一个数组,其中的每个值都表示世界的一侧:

let array = ["NORTH", "SOUTH", "WEST", "EAST"];

If NORTH/SOUTH or EAST/WEST stand together , then these values are removed (SOUTH/NORTH and WEST/EAST are removed too).如果 NORTH/SOUTH 或 EAST/WEST 站在一起,那么这些值将被删除(SOUTH/NORTH 和 WEST/EAST 也被删除)。 In this case, the function has to return empty array, instead it returns undefined.在这种情况下,函数必须返回空数组,而不是返回 undefined。 Can anyone explain why this is happening.谁能解释为什么会这样。 Sorry for the mistakes, I tried not to make them抱歉犯了错误,我尽量不犯这些错误

 let array = ["NORTH", "SOUTH", "WEST", "EAST"]; let obj = { "NORTH": 1, "SOUTH": -1, "WEST": 2, "EAST": -2 } function dirReduc(arr) { for (let i = 0; i < arr.length; i++) { if (i == arr.length - 1 || !arr.length) { return arr; } else if (obj[arr[i]] + obj[arr[i + 1]] == 0) { arr.splice(i, 2); return dirReduc(arr); } } } console.log(dirReduc(array));

When your recursive function splices away all content, like in the example, the deepest nested call of the function will not iterate the loop (as the array is empty), and return undefined .当您的递归函数拼接掉所有内容时,就像在示例中一样,函数的最深嵌套调用将不会迭代循环(因为数组为空),并返回undefined This value will be returned also from the point where the recursive call was made, and so also the main call will return undefined .该值也将从进行递归调用的点返回,因此主调用也将返回undefined

I would suggest not using recursion, but iterate backwards.我建议不要使用递归,而是向后迭代。 That way the splice call does not influence the array iteration negatively, and you'll only do one sweep over the array:这样splice调用不会对数组迭代产生负面影响,并且您只会对数组进行一次扫描:

function dirReduc(arr) {
    for (let i = arr.length-2; i >= 0; i--) {
        if (obj[arr[i]] + obj[arr[i + 1]] == 0) arr.splice(i, 2);
    }
    return arr;       
} 

You can modify is as following:您可以修改如下:

let array = ["NORTH", "SOUTH", "WEST", "EAST"];

let obj = {
    "NORTH": 1,
    "SOUTH": -1,
    "WEST": 2,
    "EAST": -2
}

function dirReduc(arr) {
    for (let i = 0; i < arr.length; i++) {
        if (i == arr.length - 1) {
            return arr;
        } else if (obj[arr[i]] + obj[arr[i + 1]] == 0) {
            arr.splice(i, 2);
            if (arr.length == 0)
                return [];
            return dirReduc(arr);       
        }
    }
} 

console.log(dirReduc(array));

Hope this helps.希望这可以帮助。

您的数组长度减少到 0,因此 for 循环甚至没有运行。

for (let i = 0; i < arr.length; i++) {

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM