函数可以调用自己叫做递归调用,不建议使用,但要清楚原理
实例:实现阶乘
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script type="text/javascript">
window.onload=function() {
function factorial(n) {
if (n == 1) {
return 1;
}
//5的阶乘=1*2*3*4 = 4的阶乘 * 4
return factorial(n - 1) * (n - 1);
}
//alert(factorial(5));
var btn = document.getElementById(‘btn‘);
var inp1 = document.getElementById("inp1");
var inp2 = document.getElementById("inp2");
btn.onclick=function () {
//alert(1);
inp2.value=factorial(inp1.value);
}
}
</script>
</head>
<body>
<input type="text" id="inp1" />的
<input type="button" id="btn" value="阶乘" />为
<input type="text" id="inp2" />
</body>
</html>
原文:https://www.cnblogs.com/chengzizhou/p/12521110.html