递归解法案例1 !DOCTYPE htmlhtml lang="en"head meta charset="UTF-8" meta name="viewport" content="width=device-width, initial-scale=1.0" titleDocument/title/headbody script function sumFunc(num, start) { num += start; start++ if (start
递归解法案例1
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
function sumFunc(num, start) {
num += start;
start++
if (start > 1000) {
console.log(num)
return num
} else {
sumFunc(num, start)
}
}
sumFunc(0, 1)
</script>
</body>
</html>
运行结果
递归简单写法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
// function sumFunc(num, start) {
// num += start;
// start++
// if (start > 1000) {
// console.log(num)
// return num
// } else {
// sumFunc(num, start)
// }
// }
// sumFunc(0, 1)
let sum=0
function sumFunc(data){
sum+=data
return data==0?sum:sumFunc(data-1)
}
console.log(sumFunc(1000))
</script>
</body>
</html>
运行结果