JavaScript-3.5-JavaScript 函数-案例
案例
一:使用函数实现计算机功能
- 使用 prompt 输入两个数和运算符号,计算两个数的操作结果
- 使用 switch 判断运算符号,调用函数计算两数结果
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>计算机</title>
</head>
<body>
<button onclick="calc">点击计算</button> <br>
</body>
<script type="text/javascript">
num1 = parseFloat(prompt("请输入第一个数:"));
fh = prompt("请输入运算符:");
num2 = parseFloat(prompt("请输入第二个数:"));
switch(fh){
case "+":
document.write(num1+" "+fh+" "+num2+" "+"="+" ");
document.write(num1+num2);
break;
case "-":
document.write(num1+" "+fh+" "+num2+" "+"="+" ");
document.write(num1-num2);
break;
case "*":
document.write(num1+" "+fh+" "+num2+" "+"="+" ");
document.write(num1*num2);
break;
case "/":
document.write(num1+" "+fh+" "+num2+" "+"="+" ");
document.write(num1/num2);
break;
default:
document.write("请重新输入");
break;
}
</script>
</html>
效果动态图
二:递归
- 计算 1+2+3+…+10
- 计算 1!+2!+3!+…+10!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>递归</title>
</head>
<body>
</body>
<script type="text/javascript">
var sum = 0;
!function(num){
sum += num;
num++;
if(num<=10){
arguments.callee(num);
}
}(1);
console.log(sum);
</script>
</html>
效果图
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>递归</title>
</head>
<body>
</body>
<script type="text/javascript">
var sum = 0,jie=1;
!function(num){
jie *= num;
sum += jie;
num++;
if(num<=10){
arguments.callee(num);
}
}(1);
console.log(sum);
</script>
</html>
效果图