Spread操作符(...),也稱作展開操作符,作用是將可迭代的(Iterable)對象進行展開。
比如有2個數組,我們要將其中一個數組中所有元素插入到另一個數組中,通過Spread操作符,就可以這樣進行:
var fruits = ["apple", "orange", "peach"];
var shoppingList = ["t-shirt", ...fruits, "egg"]; // shoppingList的值:["t-shirt", "apple", "organe", "peach", "egg"]
我們看到,通過在shoppingList中使用Spread操作符對fruits數組進行展開,就可以輕松的將fruits數組元素變成shoppingList中的數組元素,非常簡單。如果不用Spread操作符,我們也可以通過循環數組并建新數組的方式來實現,但是明顯會復雜的多。
另一個常見的場景是在函數調用傳參的時候:
function testFunc(x, y, z) {console.log(x, y, z);
}var args = [10, 15, 20];testFunc(args); //不正確
testFunc(...args); //正確
我們的testFunc()是一個接受3個參數的函數,而變量args是一個包含了3個元素的數組。如果直接把args作為參數傳入testFunc(),肯定是不符合這個函數的設計邏輯的。在這種情況下,使用Spread操作符,就可以把數組中的元素展開并填充這個函數的參數列表,達到理想中的效果。
最后,我們在一開始提到,Spread操作符可以展開Iterable的對象,這樣的話,除了數組之外,所有實現了Symbol.iterator的對象,如:Set, Map和Generator等等,都可以使用Spread操作符。
var map = new Map();
map.set("a", 1);
map.set("b", 2);
var arr1 = [...map]; //[["a", 1], ["b", 2]]var set = new Set();
set.add(1);
set.add(2);
set.add(1);
set.add(3);
var arr2 = [...set]; //[1, 2, 3]function *myGen() {yield "hello";yield "world";
}
var arr2 = [...myGen()]; //["hello", "world"]