这是我参与8月更文挑战的第9天,活动详情查看:8月更文挑战
1. ES5
中函数参数默认值的设置方式
function f (x, y, z) {
if (y === undefined) {
y = 7
}
if (z === undefined) {
z = 42
}
return x + y + z
}
console.log(f(1))
console.log(f(1, 8))
console.log(f(1, 8, 43))
/* 运行结果:
50
51
52
*/
复制代码
2. ES6
中函数参数默认值的设置方式
// 注意:没有默认值的参数写在前面,有默认值的参数写在后面
function f (x, y = 7, z = 42) {
return x + y + z
}
console.log(f(1))
console.log(f(1, 8))
console.log(f(1, 8, 43))
// 使用“undefined”实现中间参数的默认值赋值
console.log(f(1, undefined, 43))
/* 运行结果:
50
51
52
51
*/
复制代码
参数的默认值可以指定为常量,也可以是含有“前面”参数的运算表达式:
function f (x, y = 7, z = x + y) {
return x * 10 + z
}
console.log(f(1, undefined, 2)) // 1 * 10 + 2 = 12
console.log(f(1)) // 1 * 10 + (1 + 7) = 18
console.log(f(1, 9)) // 1 * 10 + (1 + 9) = 20
console.log(f(1, undefined)) // 1 * 10 + (1 + 7) = 18
/* 运行结果:
12
18
20
18
*/
复制代码
参数的默认值如果指定为含有其它参数的表达式,那么表达式中的参数必须是前面已定义的参数,所以像下面这样指定 y
参数的默认值是错误的:
function f (x, y = x + z, z = 7) { // 'z' was used before it was defined.
return x * 10 + y
}
console.log(f(1)) // Uncaught ReferenceError: Cannot access 'z' before initialization
复制代码
可以通过 arguments
查看当前函数的参数信息:
function f (x, y = 7, z = x + y) {
console.log(arguments) // 通过 arguments 查看当前函数的参数的信息
console.log(arguments.length) // 当前函数传入的参数个数
console.log(Array.from(arguments)) // 当前函数传入的参数信息,Array.from 用来转换伪数组为数组
return x * 10 + z
}
console.log(f(1, undefined, 2)) // 传了 3 个参数
console.log(f(1, 2)) // 传了 2 个参数
复制代码
上述代码的运行结果截图:
上面我们使用了 arguments
来获取当前函数传入的参数信息,但到了 ES6
中,其实是禁止使用 arguments
的,那怎么办呢?有办法,我们后面再讲,这里先讲一下如何获取“函数定义时未指定默认值的参数个数”,我们可以使用“函数名.length
”的方式实现:
function f (x, y = 7, z = x + y) { // 注意:没有默认值的参数写在前面,有默认值的参数写在后面
console.log(f.length) // 1
return x * 10 + z
}
console.log(f(1, undefined, 2))
/* 运行结果:
1
12
*/
复制代码
下面我们把上面函数参数列表中的 y
的默认值去掉,再看 f.length
的值:
function f (x, y, z = x + y) { // 注意:没有默认值的参数写在前面,有默认值的参数写在后面
console.log(f.length) // 2
return x * 10 + z
}
console.log(f(1, undefined, 2))
/* 运行结果:
2
12
*/
复制代码
总结:
arguments.length
和function.length
的区别:arguments.length
获取到的是“函数执行时接收到的参数个数”;而function.length
获取到是“函数定义时未指定默认值的参数个数(出现首个有默认值的参数前的参数个数)”。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END