<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body></body>
<script>
function sum(...args) {
console.log(args);
if (args.length == 0) {
console.log("end=====");
return 0;
}
return args.pop() + sum(...args); //这里需要将数组展开,不然就变成二维数组了。
// 优化
// return args.length == 0 ? 0 : args.pop() + sum(...args);
}
console.log(sum(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
</script>
</html>
js 递归求和
最新推荐文章于 2024-01-31 09:22:08 发布