参数扩展
function show(a, b, ...args){
console.log(a) // 3
console.log(b) // 4
console.log(args) // [5, 7, 8] 是个数组,Rest parameter 剩余参数
}
show(3,4,5,7,8)
...args 用于收集剩余参数
...args 必须放在参数末尾,否则报错:Rest parameter must be last formal parameter
展开数组
let arr = [1,2,3]
function show(a,b,c){
console.log(a)
console.log(b)
console.log(c)
}
show(...arr) //1,2,3 等价于 show(1, 2, 3)
...arr 相当于直接把数组的内容掏出来放在这
实例1、...arr
let arr1 = [1,2,3]
let arr2 = [4,5,6]
let arr3 = [...arr1, ...arr2]
alert(arr3) //[1,2,3,4,5,6]
实例2、 参数扩展和数组展开
function show(...args){ //参数扩展
fn(...args) //展开数组
}
function fn(a, b){
alert(a + b)
}
show(3,9) //12
默认参数
function show(a, b = 12, c = 14){
console.log(a, b, c)
}
show(18) //18,12,14
show(18,39) //18,39,14
show(18,39,49) //18,39,49
传参时,如果传,就依照传递的参数,如果没传,就依照默认的参数。