JS入门到精通 第4章 函数
导读:一、练习1. 练习1 (1)源代码<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>函数参数的使用</title> <script type...
一、练习
1. 练习1
(1)源代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>函数参数的使用</title>
<script type="text/javascript">
function show(bookname,author){
alert("图书名称:"+bookname+"\n图书作者:"+author);
}
</script>
</head>
<body>
<script type="text/javascript">
show("零基础学JavaScript","明日科技");
</script>
</body>
</html>(2)运行页面
https://www.xinyizhishu.top/jsC/sc/4_1/
(3)Tips
全是语法错误,莫名其妙又好了。
2. 练习2
(1)源代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>计算购物车中商品总价</title>
</head>
<body>
<script type="text/javascript">
function price(unitPrice,number){
var totalPrice=unitPrice*number;//计算单个商品总价
return totalPrice;//返回单个商品总价
}
var phone = price(5000,2);//调用函数,计算手机总价
var computer = price(4000,10);//调用函数,计算笔记本电脑总价
var total=phone+computer;//计算所有商品总价
alert("购物车中商品总价:"+total+"元");//输出所有商品总价
</script>
</body>
</html>(2)运行页面
https://www.xinyizhishu.top/jsC/sc/4_2/
(3)Tips
后面的能搞定吗?
3. 练习3
(1)源代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>函数调函数</title>
<script type="text/javascript">
function getAverage(score1,score2,score3){
var average=(score1+score2+score3)/3;
return average;
}
function getResult(score1,score2,score3){
document.write("3个评委给出的分数分别为:"+score1+"分、"+score2+"分、"+score3+"分<br>");
var result=getAverage(score1,score2,score3);
document.write("周星星的最后得分为:"+result+"分");
}
</script>
</head>
<body>
<script type="text/javascript">
getResult(91,89,93);
</script>
</body>
</html>(2)运行页面
https://www.xinyizhishu.top/jsC/sc/4_3/
(3)Tips
小意思。
4. 练习4
(1)源代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>匿名函数</title>
</head>
<body>
<script type="text/javascript">
var star=function(n){
for(var i=1;i<=n;i++){
for(var j=1;j<=n-i;j++){
// document.write("<br>i="+i);
// document.write("<br>j="+j);
// document.write("<br>n-i="+(n-i));
//
document.write(" ");//输出空格
}
for(var j=1; j<=i; j++){//定义内层for循环语句
document.write("* ");//输出*和空格
}
document.write("<br>");//输出换行标记
}
}
star(6);
</script>
</body>
</html>(2)运行页面
https://www.xinyizhishu.top/jsC/sc/4_4/
(3)Tips
还是有点别。
二、编程训练
1. 训练1
(1)源代码
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无聊</title>
<script type="text/javascript">
function address(province,city,area,detailed){
document.write(province+city+area+detailed);
}
</script>
</head>
<body>
<h2>请核对您的收货地址</h2>
<script type="text/javascript">
address("吉林省","长春市","朝阳区","工农大路51号");
</script>
</body>
</html>(2)运行页面
https://www.xinyizhishu.top/jsC/sc/4_5/
(3)Tips
我要实质。
2. 训练2
(1)源代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>绝对值函数</title>
<script type="text/javascript">
function getAbs(num){
if(num<0){
alert(num+"的绝对值是"+num*-1);
}else{
alert(num+"的绝对值是"+num);
}
}
</script>
</head>
<body>
<script type="text/javascript">
getAbs(-20);
</script>
</body>
</html>(2)运行页面
https://www.xinyizhishu.top/jsC/sc/4_6/
(3)Tips
难以理解。