学习js的第四天:函数
函数
定义:对任意功能的代码进行封装,在需要的时候进行调用
把函数比作一个盒子,盒子里面装代码,通过盒子的名称找到盒子执行里面的代码
1.盒子封装代码
2.调用盒子执行代码
语法:
function 函数名(){------------>定义函数
函数体(要执行的代码)
}
函数名()------>函数的调用语句
一、函数的作用
封装函数,封装目的:复用代码
二、函数的参数
function 函数名(形参){
要执行的代码
}
函数名(实参)
形参:定义函数时,在函数名括号中定义的变量称为形参
实参:使用函数调用语句,调用函数时,传入的实际参数值
参数个数:可以定义多个
function 函数名(m,n){
要执行的代码
}
函数名(100,200)
m,n与100,200为一一对应的关系
参数个数不匹配时:形参个数多于实参
function 函数名(m,n){
要执行的代码
}
函数名(100)
m=100,n=undefined
实参的个数多于形参:没有接收的实参无意义
三、函数的返回值:return语句
作用:终止函数,不让它执行下面的代码,返回函数调用处,继续执行下面的代码
无返回值
function 函数名(){
console.log('')
var i=0
return (终止函数)------>return后面的语句不会执行
console.log('i')
}
函数名()
有返回值
function fun(){
console.log('')
var i=0
return 100
console.log('i')
}
fun()-------->会把100返回调用处,100的值就在fun()中,即fun(100)
函数类型:根据函数参数和返回值,分为四类
1.无参无返回值:
function fun(){
函数体
}
fun()
2.有参无返回值:
function fun(m){
要执行的代码
}
fun(100)
3.无参有返回值
function fun(){
要执行的代码
return 100
}
fun()-------->返回的100,在fun中,即fun(100)
4.有参有返回
function fun(m){
console.log('')
return m+100
}
var m=fun(200)
参数的默认值:
封装函数的示例:
<!-- 封装比较两个数的大小函数 -->
<script>
function getMax() {
var a = 35
var b = 66
var max = a
if (b > max) {
max = b
console.log(max)
}
}
getMax()
</script>
<!-- 封装闰年 -->
<script>
function getMax() {
var year = 2020
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
console.log(year + '是闰年')
} else {
console.log(year + '不是闰年')
}
}
getMax()
</script>
有参数示例:
<!-- 封装比较两个数的大小函数,实参,形参 -->
<script>
function getMax(a,b) {
var max = a
if (b > max) {
max = b
console.log(max)
}
}
getMax(55,68)
</script>
返回值: