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

ing*_*ngo 2 javascript arrays recursion function

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

满足条件时,循环将正确停止。但是,只有匹配数组中的第一个键(索引0)时,它才返回键的值,而其余键则返回“ undefined”。

我的错在哪里 这是可以更好地说明的代码:

    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?!
Run Code Online (Sandbox Code Playgroud)

Raj*_*amy 5

您必须return使用递归调用的值,

  // recall with updated index
  return loop(arr,i); 
}
Run Code Online (Sandbox Code Playgroud)

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