在 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);
推荐答案
试试这个:
function rangeOfNumbers(startNum, endNum) {
if (startNum - endNum === 0) {
return [startNum];
} else {
const numbers = rangeOfNumbers(startNum + 1, endNum);
numbers.unshift(startNum);
return numbers;
}
};
相关文章