使用递归创建从大到小排列的数组
function countdown(n) {
if (n < 1) {
return []
} else {
const arr = countdown(n - 1)
arr.unshift(n)
return arr
}
}
function countdown(n) {
if (n < 1) {
return []
} else {
const arr = countdown(n - 1)
arr.splice(0, 0, n)
return arr
}
}
function countdown(n) {
return n < 1 ? [] : [n].concat(countdown(n - 1))
}
function countdown(n) {
return n < 1 ? [] : [n, ...countdown(n - 1)]
}
使用递归创建数组范围
function rangeOfNumbers(startNum, endNum) {
if (endNum - startNum === 0) {
return [startNum]
} else {
var numbers = rangeOfNumbers(startNum, endNum - 1)
numbers.push(endNum)
return numbers
}
}
function rangeOfNumbers(startNum, endNum) {
return startNum === endNum
? [startNum]
: rangeOfNumbers(startNum, endNum - 1).concat(endNum)
}
function rangeOfNumbers(startNum, endNum) {
return startNum === endNum
? [startNum]
: [...rangeOfNumbers(startNum, endNum - 1), endNum]
}