参数默认值(常用)
1.ES5设置函数默认值
function fn(name , age) {
var name = name || 'cht';
var age = age || 18;
console.log(age); // 18
// 原本我想传递的age为0 , 但是走上面的逻辑后。
// || 遇到真则返回,0为false,继续往后走取18, 所以出问题!!!!!
}
fn('cht' , 0);
注意:当参数的布尔值为false时候,则取后面,0为false
ES5中处理不确定函数参数
- 函数中的arguments拿到的是 函数参数的维数组
- 遍历函数的参数需要将维数组转换成数组 借用 call方法
function fn() {
let res = 0;
Array.prototype.forEach.call(arguments , function(item) {
res += item * 1;
})
return res;
}
console.log(fn(1,2)); // 3
扩展 Array.from方法
function fn() {
let res = 0 ;
// 使用Array.from方法,可以将伪数组转化成 数组, 然后调用数组的遍历方法
Array.from(arguments).forEach(function(item) {
res += item * 1;
})
return res;
}
console.log(fn(1,2)); // 3
2.ES6支持在定义函数的时候为其设置默认值
// ES6
function fn(name='cht' , age=18) {
//something
}
获取函数参数
函数名.length
ES6 中获取 函数的参数个数 通过 函数.length 只能获取到非默认值的参数的个数
function fn(x , y =1 , z = 2) {
console.log(f3.length); // 1
return x + y + z;
}
console.log(fn(1 , 2))
ES中对于不确定参数的处理
- 使用扩展运算符,拿到 函数参数的数组
- 调用函数遍历的方法,求和
function fn(...args) {
let res = 0;
// console.log(args); // [1,2,3,4]
args.forEach(function (item) {
res += item*1;
})
return res;
}
console.log(fn(1,2,3,4)) // 10
结合使用扩展运算符,使 函数参数得处理变得更加强大
- 第一个参数不变,使用扩展运算符,收集剩余得参数
function fn(arg1 , ...args) {
let res = 0 ;
args.forEach(function(item) {
res += item*1;
})
return arg1 + res;
}
console.log(fn(1, 2, 3, 4)); // 10
反向操作
function fn(x , y , z) {
return x+y+z;
}
let data = [1,2,3];
console.log(fn(...data)); // 6