JavaScript 中的递归归约
我对 JavaScript 很陌生,不理解它的一些行为。我想编写 Eloquent JavaScript 书中找到的 reduce 函数的递归版本。这是我的代码:
function rec_reduce( fn, base, list ) {
if( list.length === 0 ) {
return base;
}
else {
rec_reduce( fn, fn( base, list[ 0 ] ), list.slice( 1 ) );
}
}
print( rec_reduce( Math.min, 100, [ 5, 3, 7, 2, 6, 5 ] ));
结果是:
undefined
为了看看发生了什么,我把:
print( base );
作为函数的第一行,结果是:
100
5
3
3
2
2
2
undefined
谁能解释一下为什么?
I'm quite new to JavaScript and don't understand a few of its behaviours. I want to write a recursive version of reduce function found in Eloquent JavaScript book. That's my code:
function rec_reduce( fn, base, list ) {
if( list.length === 0 ) {
return base;
}
else {
rec_reduce( fn, fn( base, list[ 0 ] ), list.slice( 1 ) );
}
}
print( rec_reduce( Math.min, 100, [ 5, 3, 7, 2, 6, 5 ] ));
The result was:
undefined
To see what's going on I put:
print( base );
as a first line of the function and the result was:
100
5
3
3
2
2
2
undefined
Whould anyone explain me why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在那个
else
块中,您必须In that
else
block, you'll have to另一种方法是:
reduce_file.js:
,然后将其用作:
结果:
来自 1+2+3+4=10
Another way to do it:
reduce_file.js:
and then you use it as:
result:
from 1+2+3+4=10