本人学习过程中编写,定有不足之处,如果有错误,请您积极指正;如果有帮助,请不要吝啬您的赞美(点赞),欢迎各位大佬点赞评论。
es5中函数默认值
function sum(x,y,z){
if(y == undefined){
y = 6;
}
if(z == undefined){
z = 3;
}
return x+y+z;
}
console.log(sum(1,5,7)); //13
console.log(sum(1)); //10
很显然,es5中需在函数内部进行判断参数是否存在,增加了代码量。
es6中函数的默认值
function sum(x,y=6,z=3){
return x+y+z;
}
console.log(sum(1,5,7)); //13
console.log(sum(1)); //10
es6中的方法就简单的多。在我们没有传入某个参数时,我们可以进行以下操作:
function sum(x,y=6,z=3){
return x+y+z;
}
console.log(sum(1,undefined,7)); //14
补充知识
arguments
以伪数组的形式返回函数执行时你所填写的参数
function sum(x,y=6,z=3){
console.log(arguments);
return x+y+z;
}
console.log(sum(1,undefined,7));
f.length
返回函数中无默认值的参数的个数;
function sum(x,y=6,z=3){
console.log(sum.length); //x没有默认值
return x+y+z;
}
console.log(sum(1,undefined,7));