# 初识

``````function sum(...params) {
if (params.length === 1) { // 最小规模
return params[0]
}
return params[0] + sum2(...params.splice(1)) // 调用自身
}
console.log(sum2(1, 2, 3, 4, 5)) // 15

• 1.递归算法必须有一个基本结束条件
• 2.递归算法必须能改变状态向基本结束条件演进
• 3.递归算法必须调用自身

# 应用

## 应用1：任意进制的转换

``````// 进制互相转换
function binaryConversion(number, binary) {
const base = '0123456789ABCDEF';
if (number < binary) { // 基本结束条件
return base[number];
}
return (
binaryConversion(number / binary, binary) + base[number % binary]; // 调用自身
)
}

## 应用2：汉诺塔

``````function move(height, fromPole, withPole, toPole) {
if (height >= 1) {
move(height - 1, fromPole, toPole, withPole)
moveResult(height, fromPole, toPole)
move(height - 1, withPole, fromPole, toPole)
}
}
function moveResult(height, fromPole, toPole) {
console.log(`disk[\${height}] from \${fromPole} to \${toPole}`)
}
move(3, '#1', '#2', '#3')

/* 结果
disk[1] from #1 to #3
disk[2] from #1 to #2
disk[1] from #3 to #2
disk[3] from #1 to #3
disk[1] from #2 to #1
disk[2] from #2 to #3
disk[1] from #1 to #3
*/