1.函数参数的默认值
1.1 基本用法
- 形参初始值 具有默认值的参数, 一般位置要靠后
function add(a,b,c=10) {
return a + b + c;
}
let result = add(1,2);
console.log(result); // 13
- 与
解构赋值
结合
function foo({x, y = 5}) {
console.log(x, y);
}
foo({}) // undefined 5
foo({x: 1}) // 1 5
foo({x: 1, y: 2}) // 1 2
foo() // TypeError: Cannot read property 'x' of undefined
1.2 函数的 length 属性
- 指定了默认值以后,函数的
length
属性,将返回没有指定默认值的参数个数
(function (a) {}).length // 1
(function (a = 5) {}).length // 0
(function (a, b, c = 5) {}).length // 2
2.rest 参数
- ES6 引入
rest
参数(形式为...变量名
),用于获取函数的多余参数,这样就不需要使用arguments
对象了 - rest 参数搭配的变量是一个数组,该变量将
多余
的参数放入数组中
function add(...values) {
let sum = 0;
for (var val of values) {
sum += val;
}
return sum;
}
add(2, 5, 3) // 10
- 注意,rest 参数之后不能再有其他参数,否则会报错
function f(a, ...b, c) {
// ...
}
- 函数的
length
属性,不包括 rest 参数
(function(a) {}).length // 1
(function(...a) {}).length // 0
(function(a, ...b) {}).length // 1
3.扩展运算符
3.1 含义
- 扩展运算符(spread)也是三个点(
...
) - 它好比 rest 参数的逆运算,将一个数组转为用逗号分隔的参数序列
console.log(...[1, 2, 3])
// 1 2 3
console.log(1, ...[2, 3, 4], 5)
// 1 2 3 4 5
3.2 应用
- 复制数组
const a1 = [1, 2];
// 写法一
const a2 = [...a1];
// 写法二
const [...a2] = a1;
- 合并数组
const arr1 = ['a', 'b'];
const arr2 = ['c'];
const arr3 = ['d', 'e'];
[...arr1, ...arr2, ...arr3]
// [ 'a', 'b', 'c', 'd', 'e' ]
- 与解构赋值结合
const [first, ...rest] = [1, 2, 3, 4, 5];
first // 1
rest // [2, 3, 4, 5]
const [first, ...rest] = [];
first // undefined
rest // []
const [first, ...rest] = ["foo"];
first // "foo"
rest // []
- 字符串
扩展运算符还可以将字符串转为真正的数组
[...'hello']
// [ "h", "e", "l", "l", "o" ]
- 实现了 Iterator 接口的对象
任何定义了遍历器(Iterator
)接口的对象,都可以用扩展运算符转为真正的数组
let nodeList = document.querySelectorAll('div');
let array = [...nodeList];