【发布时间】:2016-07-04 07:47:45
【问题描述】:
我正在尝试使用递归函数循环数组。 如果它与给定的正则表达式模式匹配,则循环应该停止并返回键的值。
当条件满足时循环正确停止。但是,它仅在数组中的第一个键(索引 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?!
【问题讨论】:
标签: javascript arrays function recursion