[英]Why Does My Recursive Function Return Undefined?
I don't understand why return weights_data
returns undefined
, and console.log(weights_data)
returns something.我不明白为什么
return weights_data
返回undefined
,而console.log(weights_data)
返回一些东西。
const getWeightReattributeProportionally = (weights_data, weight, z = 0) => {
weights_data.forEach( (r, i) => weights_data[i] = (r * weight) + r );
if ( weights_data.reduce( (a, b) => a + b) >= 0.9999999999999999 ) {
console.log(weights_data);
return weights_data;
} else {
getWeightReattributeProportionally(weights_data, weight *= weight, z += 1);
}
}
const data = [0.12, 0.22, 0.32, 0.18]
const aaaa = getWeightReattributeProportionally(data, 0.16)
console.log(aaaa)
You forgot that you need to return the result of the recursive function:你忘了你需要返回递归函数的结果:
const func = (weights_data, weight, z = 0) => { weights_data.forEach((r, i) => weights_data[i] = (r * weight) + r) if (weights_data.reduce((a, b) => a + b) >= 0.9999999999999999) { console.log(weights_data) return weights_data } else { return func(weights_data, weight *= weight, z += 1) // NEW! } } const data = [0.12, 0.22, 0.32, 0.18] const aaaa = func(data, 0.16) console.log(aaaa)
Also, you have a bug in your code: z
is never used anywhere in your function此外,您的代码中有一个错误:
z
从未在您的函数中的任何地方使用
Unless your recursive function uses side effects (eg, manipulating global/shared state, writing to a file, etc.) to do its job, every invocation, including the outermost, must return its results to its caller.除非您的递归函数使用副作用(例如,操作全局/共享状态,写入文件等)来完成其工作,否则每次调用,包括最外层的调用,都必须将其结果返回给其调用者。
If it doesn't, how can the caller know what the recursive call did?如果没有,调用者如何知道递归调用做了什么?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.