《JavaScript高级程序设计》在讲Function类型时说:
说起来ECMAScript中什么最有意思,我想那莫过于函数了。
其中有意思的地方之一:rest参数。
我们知道,ES6支持类(class)这种写法了:
class A {
constructor(x, y) {
this._x = x;
this._y = y;
}
}
如果是C++,在对象初始化时如果想指定不同的方式来初始化数据成员,可以重载构造函数,然后在定义新对象时,编译器根据实参类型决定使用哪个构造函数。
而JavaScript没有函数重载,如何实现支持多种初始化方式呢?
首先,JS函数的参数与大多数其他语言中函数的参数有所不同,即便刚开始只定义了两个参数,在调用时也未必一定要传两个,可以传一个或者三个。
在函数体内,它可以通过一个对象来获取所有参数,这个对象是:arguments。比如:
function sayHi() {
alert("hello " + arguments[0] + "," + arguments[1]);
}
到了ES6,又引入了rest参数,形式为:...变量名。arguments对象不是数组,只是可以下标访问而已,而rest参数是一个真正的数组。
使用rest参数,上面的构造函数可以这样写:
class A {
constructor(...args) {
if (args.length == 3) {
this._x = args[0];
this._y = args[1];
this._z = args[2];
}
else if (args.length == 2) {
this._x = args[0];
this._y = args[1];
this._z = 0;
}
else {
throw TypeError("args error!");
}
}
}
函数的rest 参数示例
ES6 引入 rest 参数(形式为…变量名),用于获取函数的多余参数,这样就不需要使用arguments对象了。rest 参数搭配的变量是一个数组,该变量将多余的参数放入数组中。
function test() {
return arguments;
}
test(2, 5, 3) // [2, 5, 3]的伪数组
function test(...values) {
return values;
}
test(2, 5, 3) // [2, 5, 3]
数组的扩展运算符示例
相当于 rest 参数的逆运算,将一个数组转为用逗号分隔的参数序列。
console.log(...[1, 2, 3])
// 1 2 3
[...[1,2,3], 4]
// [1, 2, 3, 4]
运用:
function push(array, ...items) {
array.push(...items);
}
function add(x, y) {
return x + y;
}
const numbers = [4, 38];
add(...numbers) // 42
注意:
只有函数调用时,扩展运算符才可以放在圆括号中,否则会报错。
(...[1, 2])
// Uncaught SyntaxError: Unexpected number
console.log((...[1, 2]))
// Uncaught SyntaxError: Unexpected number
console.log(...[1, 2])
// 1 2
对象的扩展运算符示例
取出参数对象的所有可遍历属性,拷贝到当前对象之中。
let { x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 };
x // 1
y // 2
z // { a: 3, b: 4 }
对象的扩展运算符等同于使用Object.assign()方法:
let aClone = { ...a };
// 等同于
let aClone = Object.assign({}, a);
扩展运算符可以用于合并两个对象:
let ab = { ...a, ...b };
// 等同于
let ab = Object.assign({}, a, b)
参考文章:
https://blog.csdn.net/weixin_43972437/article/details/106022308
https://blog.csdn.net/liminwang0311/article/details/84308397
来源:oschina
链接:https://my.oschina.net/jamesview/blog/4816263