gpt4 book ai didi

Javascript:递归函数为现有值返回未定义

转载 作者:行者123 更新时间:2023-11-29 16:51:04 24 4
gpt4 key购买 nike

我正在尝试使用递归函数循环数组。如果它匹配给定的正则表达式模式,循环应该停止并返回键的值。

当条件满足时循环正确停止。但是,它仅在数组中的第一个键(索引 0)发生匹配时才返回键的值,并为其余键返回“未定义”。

我哪里错了?下面是更好说明的代码:

    function loop(arr,i) {
var i = i||0;
if (/i/gim.test(arr[i])){
console.log("key value is now: " + arr[i])
return arr[i]; // return key value
}
// test key value
console.log("key value: " + arr[i]);

// update index
i+=1;

// recall with updated index
loop(arr,i);
}

console.log( loop(["I","am", "lost"]) );
// "key value is now: I"
// "I" <-- the returned value

console.log( loop(["am", "I", "lost"]) );
// "key value: am"

// "key value is now: I" <-- test log
// undefined <-- but the return value is undefined! why?!

最佳答案

您必须从递归调用中返回值,

  // recall with updated index
return loop(arr,i);
}

loop 函数的最后一次调用将返回一个值,但同一函数的其他调用返回undefined。所以最后你得到了 undefined

关于Javascript:递归函数为现有值返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36069423/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com