ES5与ES6函数默认值与函数参数变化
1.rest参数替代arguments对象
arguments是函数实参的集合,它不是一个数组,箭头函数没有arguments对象
rest参数语法:function(...values){
//values是实参数组
}
实例对比:
<script>
function fn() {
// prompt("哥们请传参")
let len = arguments.length;
if (len == 0) {
return "哥们请传参";
}
else if (len == 1) {
return arguments[0]
}
else if (len == 2) {
return arguments[0] + arguments[1]
}
else if (len == 3) {
return arguments[0] * arguments[1] * arguments[2]
}
else if (len == 4) {
return (arguments[0] + arguments[1] + arguments[2] + arguments[3]) / 4
}
else {
let arr = [];
for (let j = 0; j < len; j++) {
arr.push(arguments[j])
}
return arr
}
}
console.log(fn())
console.log(fn(10))
console.log(fn(10, 20))
console.log(fn(10, 20, 30))
console.log(fn(10, 20, 30, 40))
console.log(fn(10, 20, 30, 40, 50, 60))
</script>
<!-- rest参数替代arguments -->
<script>
function fn(...value) {
// prompt("哥们请传参")
let len = value.length;
if (len == 0) {
return "哥们请传参";
}
else if (len == 1) {
return value[0]
}
else if (len == 2) {
return value[0] + value[1]
}
else if (len == 3) {
return value[0] * value[1] * value[2]
}
else if (len == 4) {
return (value[0] + value[1] + value[2] + value[3]) / 4
}
else {
return value
}
}
console.log(fn())
console.log(fn(10))
console.log(fn(10, 20))
console.log(fn(10, 20, 30))
console.log(fn(10, 20, 30, 40))
console.log(fn(10, 20, 30, 40, 50, 60))
</script>
2.默认参数写法:
es5:语法:形参 = 实参 || 默认值;有实参时调用实参,没有参数使用默认值
<script>
function fn(num1,num2){
// 设置默认参数
num1 = num1 || 10;
num2 = num2 || 20
return num1+num2;
}
console.log(fn());//30
console.log(fn(100,200));//300
</script>
es6:语法:function 函数名(形参,形参1="默认值2",形参2="默认值2"){},没有默认值的形参必须放在有默认值的形参前面
<script>
function foo(c,a=10,b=20){
return a+b+c;
}
console.log(foo())//NaN,因为c为undefined
console.log(foo(100))//130
console.log(foo(100,200))//320
</script>