es6數(shù)組可以用展開符。展開符“…”會將可迭代對象展開到其單獨的元素中,而所謂的可迭代對象就是任何能用“for of”循環(huán)進行遍歷的對象,例如數(shù)組、字符串、Map 、Set;當展開符用于數(shù)組,可以將一個數(shù)組轉(zhuǎn)為用逗號分隔的參數(shù)序列。
前端(vue)入門到精通課程:進入學習
Apipost = Postman + Swagger + Mock + Jmeter 超好用的API調(diào)試工具:點擊使用
本教程操作環(huán)境:windows7系統(tǒng)、ECMAScript 6版、Dell G3電腦。
展開符(擴展操作符) …
是ES6中引入的,將可迭代對象展開到其單獨的元素中,所謂的可迭代對象就是任何能用for of循環(huán)進行遍歷的對象,例如:數(shù)組、字符串、Map 、Set 、DOM節(jié)點等。
展開運算符(spread operator)允許一個表達式在某處展開。展開運算符在多個參數(shù)(用于函數(shù)調(diào)用)或多個元素(用于數(shù)組字面量)或者多個變量(用于解構(gòu)賦值)的地方可以使用。
es6展開符的使用(數(shù)組方面)
1、復制數(shù)組
給定一個數(shù)組,想要將一個數(shù)組的成員復制到另一個數(shù)組中,該怎么做?
const a = [1, 2]; const b = a; console.log(b); // [1, 2]
真有表面上這么簡單嗎?試著修改一下a數(shù)組中的值
a[0] = 3; console.log(b); // [3, 2]
誒?怎么我修改了a數(shù)組中的值,結(jié)果b數(shù)組中的值也變了?這里涉及到的是堆棧的原理,就不具體展開說了,你只需要知道簡單地使用兩邊相等的方式是不能完成數(shù)組的復制的,這里使用展開運算符就可以完成啦?
const a = [1, 2]; const c = [...a]; console.log(c); // [1, 2] a[0] = 3; console.log(c); // [1, 2]
2、合并數(shù)組
const a = [1, 2]; const b = [3]; const c = [4, 5]; console.log([...a, ...b, ...c]); // [1, 2, 3, 4, 5] console.log([...c, ...a, ...b]); // [4, 5, 1, 2, 3] console.log([99, ...a, 24, ...b, ...c]); // [99, 1, 2, 24, 3, 4, 5]
3、字符串轉(zhuǎn)為數(shù)組
前置知識:字符串可以按照數(shù)組的形式展開?
const name = 'Jae'; console.log(...name); // J a e
字符串轉(zhuǎn)數(shù)組除了用 split()
方法,也可以用展開運算符?
const name = 'Jae'; const name_string = [...name]; console.log(name_string); // ["J", "a", "e"]
4、常見的類數(shù)組轉(zhuǎn)化為數(shù)組
為什么要將類數(shù)組轉(zhuǎn)化為數(shù)組呢?因為類數(shù)組不能使用數(shù)組的方法,將其轉(zhuǎn)化過來對于一些對數(shù)據(jù)進行處理的需求就更加方便了 ~
-
arguments
function func() { console.log(arguments); } func(1, 2); // Arguments(2) [1, 2, callee: ?, Symbol(Symbol.iterator): ?] // 使用展開遠算符 function func() { console.log([...arguments]); } func(1, 2); // [1, 2]
-
NodeList
<!--HTML代碼--> <p>1</p> <p>2</p> <p>3</p>
const a = document.querySelectAll("p"); console.log(a); // NodeList(3) [p, p, p] console.log([...a]); // [p, p, p]
【