函数 function
命名:小驼峰命名,前缀为动词
一般给形参默认值
求和
<script>
function getSum(start = 0,end = 0){
let sum = 0
for (let i = start; i <= end; i++) {
sum += i
}
document.write(sum)
}
getSum(1,100)
getSum()
</script>
求数组最大值
<script>
let arr = [1,2,3,4,5,6,7,8,9]
function getSum(arr = []){
arr.sort(function (a, b){
return a - b
})
return arr[arr.length-1]
}
document.write(getSum(arr))
</script>
返回多个数据 用数组
函数命名重复,调用就近原则
实参 形参不匹配
1.实参多余形参 多余的忽略
2.实参少于形参 自动填上undefined
变量特殊情况说明:
函数内部,变量没有声明,直接赋值 ,可以当全部变量看
<script>
function fn(){
num = 10
}
fn()
document.write(num)
</script>
匿名函数
1.函数表达式:
与具名函数不同,得先声明在使用。
具名函数可以先使用,再使用。
<script>
let fn = function (){
}
fn()
</script>
2.立即执行函数(加分号):
防止变量污染,变量之间不相互影响
<script>
(function (){
let num =10
})();
(function (){
let num = 20
})();
</script>
<script>
//写法一
(function (x = 0,y = 0){
console.log(x + y)
})(1 ,2);
//写法二
(function (x = 0,y = 0){
document.write(x + y)
}(1,2));
</script>
函数小练:输入秒数转化为时分秒
<script>
let second = + prompt(`输入秒数:`)
function getTime(second = 0){
//不用let 直接当全局变量
let h = parseInt(second / 60 / 60 %24)
let m = parseInt(second / 60 %60)
let s = parseInt(second % 60)
h = h > 10 ? h : '0' + h
m = m > 10 ? m : '0' + m
s = s > 10 ? s : '0' + s
return `${h}时${m}分${s}秒`
}
document.write( getTime(second))
</script>
函数形参给默认值第二种写法(逻辑中断)
<script>
function fn1(x = 0, y = 0){
return x + y
}
document.write(fn1())
function fn(x ,y){
x = x || 0
y = y || 0
return x + y
}
document.write(fn())
</script>
逻辑中断
<script>
document.write(11 && 22) //22 真真结果为第二个 假真结果第一个
document.write(true && 22) //22
document.write(undefined && 11) //undefined
document.write(11 || 22) //11 假假结果为第二个 真假结果为第一个
document.write(undefined || 22) //22
document.write(true || 11) //true
</script>
转化为布尔
字符串 ‘’ 数字 0 undefined null false NaN 为假
<script>
document.write(Boolean('')) //false
document.write(Boolean(0)) //false
document.write(Boolean(undefined)) //false
document.write(Boolean(NaN)) //false
document.write(Boolean(null)) //false
document.write(Boolean([])) //true
</script>
隐式转换
1.有字符串的加法 “”+1 ,结果是"1"
2.减法 只能用于数字,会使空字符串""转化为0
3.null经过数字转换之后为0
4.undefined经过数字转换之后变为NaN
<script>
console.log('' + 1) //'1'
console.log('' - 1) // -1
console.log(undefined + 1) // NaN
console.log(null + 1) //1
console.log(null == undefined) //true
console.log(null == 0) //false
console.log(undefined == NaN) //false
</script>
特殊:Null == undefined 为true