Javascript:递归函数返回未定义的现有值 [英] Javascript: recursive function returns undefined for existing value
问题描述
我正在尝试使用递归函数循环数组. 如果循环与给定的正则表达式模式匹配,则循环应停止并返回键的值.
I am trying to loop an array using a recursive function. The loop should stop and return the value of the key, if it matches a given regex pattern.
满足条件时,循环将正确停止.但是,只有在数组中的第一个键(索引为0)匹配时,它才返回键的值,而其余键则返回"undefined".
The loop stops correctly when the condition is met. However, it only returns the key's value if the match occurs for the first key (index 0) in the array and returns 'undefined' for the rest.
我的错误在哪里?这是可以更好地说明的代码:
Where's my mistake? Here's the code to better illustrate:
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?!
推荐答案
您必须return
递归调用中的值,
You have to return
the value from the recursive call,
// recall with updated index
return loop(arr,i);
}
对函数loop
的最终调用将返回一个值,但对同一函数的其他调用将返回undefined
.所以最后您最终得到了undefined
The final call for the function loop
will return a value, but the other calls for the same function returns undefined
. So finally you end up in getting undefined
这篇关于Javascript:递归函数返回未定义的现有值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!