JS rest參數和擴展運算符...

ES6裏面新增了擴展運算符... 該運算符主要用於函數調用數組

以下:bash

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

function push(array, ...items) { array.push(...items); } 擴展運算符能夠看作是rest參數的逆運算,將數組轉爲逗號隔開的參數序列this

什麼是rest參數,其實這個東西在ES6以前咱們也常常用,那就是function內部保存spa

參數的對象argumentsrest

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

不過arguments不是數組而是對象,只是經過下標方式訪問而已。有了擴展運算符...,咱們能夠將參數變得比arguments更加靈活。對象

例如:string

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!");
        }
    }
}
複製代碼
相關文章
相關標籤/搜索