ES6特性之:Spread操作符
Spread操作符(...),也稱作展開操作符,作用是將可迭代的(Iterable)對象進行展開。
比如有2個數(shù)組,我們要將其中一個數(shù)組中所有元素插入到另一個數(shù)組中,通過Spread操作符,就可以這樣進行:
var fruits = ["apple", "orange", "peach"]; var shoppingList = ["t-shirt", ...fruits, "egg"]; // shoppingList的值:["t-shirt", "apple", "organe", "peach", "egg"]我們看到,通過在shoppingList中使用Spread操作符對fruits數(shù)組進行展開,就可以輕松的將fruits數(shù)組元素變成shoppingList中的數(shù)組元素,非常簡單。如果不用Spread操作符,我們也可以通過循環(huán)數(shù)組并建新數(shù)組的方式來實現(xiàn),但是明顯會復雜的多。
另一個常見的場景是在函數(shù)調(diào)用傳參的時候:
function testFunc(x, y, z) {console.log(x, y, z); }var args = [10, 15, 20];testFunc(args); //不正確 testFunc(...args); //正確我們的testFunc()是一個接受3個參數(shù)的函數(shù),而變量args是一個包含了3個元素的數(shù)組。如果直接把args作為參數(shù)傳入testFunc(),肯定是不符合這個函數(shù)的設計邏輯的。在這種情況下,使用Spread操作符,就可以把數(shù)組中的元素展開并填充這個函數(shù)的參數(shù)列表,達到理想中的效果。
最后,我們在一開始提到,Spread操作符可以展開Iterable的對象,這樣的話,除了數(shù)組之外,所有實現(xiàn)了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"]總結(jié)
以上是生活随笔為你收集整理的ES6特性之:Spread操作符的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: data.frame类型数据如何将第一列
- 下一篇: Android 那些年,处理getAct