Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
262 views
in Technique[技术] by (71.8m points)

javascript - 使用JavaScript中的递归获取范围号(Getting range numbers using recursion in JavaScript)

I am trying to get the range of numbers using recursion.(我正在尝试使用递归来获取数字范围。)

Can someone explain to me why it isn't working?(有人可以向我解释为什么它不起作用吗?) function range(x,y){ var results = []; if(x === y){ return results; } return results.push(range(x + 1,y)); } range(1,5);   ask by spaceDog translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The beauty of recursion is that you don't need local variables ( var results ).(递归的好处在于您不需要局部变量( var results )。)

You just pass state as arguments to each recursive iteration:(您只需将状态作为参数传递给每个递归迭代:) const concat = (xs, y) => xs.concat(y); const range = (x, y) => { const rec = (x, y, acc) => x < y ? rec(x + 1, y, concat(acc, x)) : acc; return rec(x, y, []); } ES5 version in case you aren't familiar with the arrow syntax:(ES5版本,以防您不熟悉箭头语法:) function concat(xs, y) { return xs.concat(y); } function range(x, y) { function rec(x, y, acc) { return x < y ? rec(x + 1, y, concat(acc, x)) : acc; } return rec(x, y, []); } That isn't the most elegant solution though!(那不是最优雅的解决方案!) With recursion we can simply build up the stack with each recursive call.(使用递归,我们可以在每次递归调用时简单地建立堆栈。) Each stack frame contains a computed partial result.(每个堆栈帧包含一个计算的部分结果。) Then we just need to unwind the stack and attach each partial result to an array:(然后,我们只需要展开堆栈并将每个部分结果附加到数组:) const range = (x, y) => x < y ? [x].concat(range(x + 1, y)) : []; Or more functional:(或更实用:) const concat = (xs, y) => xs.concat(y); const range = (x, y) => x < y ? concat([x], range(x + 1, y)) : []; Note that concat([x], range(x + 1, y)) is the recursive case and [] the base case.(请注意, concat([x], range(x + 1, y))是递归情况, []是基本情况。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...