1、函数的概念
2、函数的使用
2.1、声明函数
2.2、调用函数
2.3、函数的封装
2.4、案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
function getSum() {
var sum = 0;
for(var i=1;i<=100;i++){
sum +=i;
}
console.log(sum);
}
getSum();
</script>
</head>
<body>
</body>
</html>
3、函数的参数
3.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>
<script>
function getSum(num1,num2){
console.log(num1+num2);
}
getSum(1,3);
function getSums(num1,num2){
var sum = 0;
for(var i = num1;i<=num2;i++){
sum +=i;
}
console.log(sum);
}
getSums(1,100);
</script>
</head>
<body>
</body>
</html>
3.2、形参和实参不匹配的问题
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
function getSum(num1,num2){
console.log(num1+num2);
}
getSum(1,2);
getSum(1,2,3);
getSum(1);
</script>
</head>
<body>
</body>
</html>
3.3、小结
4、函数的返回值
4.1、return语句
4.2、案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
function getArrMax(arr){
var max = arr[0];
for(var i =1;i<=arr.length;i++){
if(arr[i]>max){
max = arr[i];
}
}
return max;
}
var re = getArrMax([100,1,2,4,1000]);
console.log(re);
</script>
</head>
<body>
</body>
</html>
4.3、return 可以终止函数,并且只能返回一个值
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
function getSum(num1,num2){
return num1 + num2;
alert('我是不会被执行的哦')
}
console.log(getSum(1,1));
function fn(num1,num2){
return num1,num2;
}
console.log(fn(1,2));
function getResult(num1,num2){
return [num1+num2,num1-num2,num1*num2,num1/num2]
}
var re = getResult(1,2);
console.log(re);
</script>
</head>
<body>
</body>
</html>
4.4、函数没有return返回undefined
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
function fun1(){
return 666;
}
console.log(fun1());
function fun2(){
}
console.log(fun2());
</script>
</head>
<body>
</body>
</html>
4.5、break,return、continue的区别
5、练习题
|