函数参数的默认值
1. ES5及之前给函数参数设置默认值
function foo(m, n) {
m = m || "aaa";
n = n || "bbb";
console.log(m, n);
}
//写法麻烦,阅读性差 且有bug
foo(0, ""); // aaa bbb
foo(null, NaN); // aaa bbb
像0 '' null NaN 这些被转换为布尔值为false的值,作为参数传给foo,依然会取默认值
2. ES6给函数参数设置默认值:
- 至于在传入的参数为undefined时,才会使用参数的默认值
- 函数调用时,不传参数,默认传入的参数就是undefined
function bar(m = "aaa", n = "bbb") {
console.log(m, n);
}
bar(0, ""); // 0 ''
bar(null, NaN); // null, NaN
bar(undefined,undefined) // aaa bbb
bar() // aaa bbb
对象参数和默认值以及解构
function printInfo({ name, age } = { name: "why", age: 18 }) {
console.log(name, age);
}
printInfo(); //why 18
printInfo({ name: "kobe", age: 40 }); //kobe 40
另一种写法
function printInfo1({ name = 'why', age = 18 } = {}) {
console.log(name, age);
}
printInfo1(); //why 18
printInfo1({ name: "kobe", age: 40 }); //kobe 40
有默认值的参数最好放到最后
function baz(m = "aaa", n, z) {
console.log(m, n, z);
}
baz(undefined, "bbb", "ccc"); //aaa bbb ccc
function baz(n, z, m = "aaa") {
console.log(m, n, z);
}
baz("bbb", "ccc"); //aaa bbb ccc
函数的length属性
- 为函数的形参的个数
- 如果某个参数有默认值,此参数及其后的参数,不计算在length中
function sum(m, n) {
return m + n;
}
console.log(sum.length); //2
function mul(x, y, z) {
return x * y * z;
}
console.log(mul.length); //3
function foo(x, y, z = 1) {}
console.log(foo.length); //2 如果某个参数有默认值,此参数及其后的参数,不计算在length中
function bar(x, y, z = 1, a, b, c) {}
console.log(bar.length); //2 如果某个参数有默认值,此参数及其后的参数,不计算在length中
函数的剩余参数(res parameter)
- ES6引入了剩余参数(res parameter)
- 可以将不定数量的参数放入到一个数组中
- 如果最后一个参数是以...为前缀的,那么它会将剩余的参数放到该参数中,并且作为一个数组
- 剩余参数必须放到最后一个,否则会报错
function foo(m,n,...arg) {
console.log(m,n,arg)
}
foo(1,2,3,4,5,6)
//1 2 [ 3, 4, 5, 6 ]
剩余参数和arguments的区别:
- 剩余参数只包含那些没有对应形参的实参,而arguments包含了传给函数的所有实参
- arguments对象并不是一个真正的数组,而rest参数是一个真正的数组,可以进行数组的所有操作
- arguments是早期的ECMAScript中为了方便去获取所有的参数提供的一个数据结构,res参数是ES6提供的并且希望依次替代arguments的
function bar(m,n,...arg) {
console.log(arg)
console.log(arguments)
}
bar(1,2,3,4,5,6,)
// [ 3, 4, 5, 6 ]
// [Arguments] { '0': 1, '1': 2, '2': 3, '3': 4, '4': 5, '5': 6 }
箭头函数补充
- 函数中没有this和arguments,会去其上级作用域中寻找
- 没有显式原型对象,所以不能作为构造函数,使用new去创建对象
const foo = () => {};
console.log(foo.prototype); //undefined
const f = new foo(); //TypeError: foo is not a constructor
非常感谢王红元老师的深入JavaScript高级语法让我学习到很多 JavaScript
的知识
网友评论