JS rest参数和扩展运算符...

414 阅读1分钟

ES6里面新增了扩展运算符... 该运算符主要用于函数调用

如下:

console.log(...[1, 2, 3])

function push(array, ...items) { array.push(...items); } 扩展运算符可以看做是rest参数的逆运算,将数组转为逗号隔开的参数序列

什么是rest参数,其实这个东西在ES6之前我们也经常用,那就是function内部保存

参数的对象arguments

function sayHi() { alert("hello " + arguments[0] + "," + arguments[1]); }

不过arguments不是数组而是对象,只是通过下标方式访问而已。有了扩展运算符...,我们可以将参数变得比arguments更加灵活。

例如:

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!");
        }
    }
}