ES6陣列的擴充套件--擴充套件運算子
1.擴充套件運算子
擴充套件運算子(spread)是三個點(...)。它好比 rest 引數的逆運算,將一個數組轉為用逗號分隔的引數序列。
{
console.log(...[1, 3, 2, 43]);//1,3,2,43
console.log(1, 2, ...[2, 5, 4], 9);//1,2,2,5,4,9
let div = document.querySelectorAll('div');
console.log(...div)
}
該運算子主要用於函式呼叫
{ function push(array, ...items) { array.push(...items); } function add(x, y) { return x + y; } const numbers = [4, 38]; console.log(add(...numbers)) // 42 }
上面程式碼中,array.push(...items)和add(...numbers)這兩行,都是函式的呼叫,它們的都使用了擴充套件運算子。該運算子將一個數組,變為引數序列。
擴充套件運算子與正常的函式引數可以結合使用,非常靈活。
{
function f(v, w, x, y, z) { }
const args = [0, 1];
f(-1, ...args, 2, ...[3]);
}
擴充套件運算子後面還可以放置表示式。
{ let x = 2; let arrrA = [2, 3, 4] let arr = [...([x > 0 ? [...arrrA] : []]), 23] console.log(arr) }
如果擴充套件運算子後面是一個空陣列,則不產生任何效果。
{
// (...[1,2])
// Uncaught SyntaxError: Unexpected number
// console.log((...[1,2]))
// Uncaught SyntaxError: Unexpected number
}
上面兩種情況都會報錯,因為擴充套件運算子所在的括號不是函式呼叫,而console.log(...[1, 2])就不會報錯,因為這時是函式呼叫。
2.替代函式的 apply 方法
由於擴充套件運算子可以展開陣列,所以不再需要apply方法,將陣列轉為函式的引數了。
{
function add(x, y, j) {
return x + y + j;
}
// es5
console.log(add.apply(null, [1, 2, 3]));
// es6
console.log(add(...[1, 2, 3]));
}
下面是擴充套件運算子取代apply方法的一個實際的例子,應用Math.max方法,簡化求出一個數組最大元素的寫法。
{
// es5
console.log(Math.max.apply(null, [1, 2, 43, 2, 3, 212]));
// es6
console.log(Math.max(...[1, 2, 43, 2, 3, 212, 56]))
// 等同於
Math.max(14, 3, 77);
}
另一個例子是通過push函式,將一個數組新增到另一個數組的尾部
{
let arr1 = [1, 2, 32, 1, 2, 4],
arr2 = [5, 3, 6, 4, 2, 4];
// es5
Array.prototype.push.apply(arr1, arr2);
console.log(arr1)
// es6
arr1.push(...arr2)
console.log(arr1)
}
3.擴充套件運算子的應用
(1)複製陣列
陣列是複合的資料型別,直接複製的話,只是複製了指向底層資料結構的指標,而不是克隆一個全新的陣列。
{
let arr1 = [1, 2],
arr2 = [];
arr2 = arr1;
console.log(arr2);//[1,2]
arr1[0] = 2;
console.log(arr2) //[2,2]
}
ES5 只能用變通方法來複制陣列
{
let arr1 = [1, 2],
arr2 = [];
let a1 = [1, 2];
let a2 = a1.concat();
a2[0] = 2;
a1 // [1, 2]
}
上面程式碼中,a1會返回原陣列的克隆,再修改a2就不會對a1產生影響。
{
let a1 = [1, 2];
// 寫法一
let a2 = [...a1];
// 寫法二
let [...a2] = a1;
}
上面的兩種寫法,a2都是a1的克隆
(2)陣列的合併
擴充套件運算子提供了數組合並的新寫法。
{
let arr1 = ['a', 'b'];
let arr2 = ['c'];
let arr3 = ['d', 'e'];
// ES5 的合併陣列
arr1.concat(arr2, arr3);
// [ 'a', 'b', 'c', 'd', 'e' ]
// ES6 的合併陣列
[...arr1, ...arr2, ...arr3]
// [ 'a', 'b', 'c', 'd', 'e' ]
}
// 不過,這兩種方法都是淺拷貝,使用的時候需要注意。
{
let a1 = [{ foo: 1 }];
let a2 = [{ bar: 2 }];
let a3 = a1.concat(a2);
let a4 = [...a1, ...a2];
a3[0] === a1[0] // true
a4[0] === a1[0] // true
}
上面程式碼中,a3和a4是用兩種不同方法合併而成的新陣列,但是它們的成員都是對原陣列成員的引用,這就是淺拷貝。如果修改了原陣列的成員,會同步反映到新陣列。
(3)與解構賦值結合
擴充套件運算子可以與解構賦值結合起來,用於生成陣列。
{
let res = ['b', 'c'], a = ['a'], list = [];
// ES5
a = list[0], rest = list.slice(1);
console.log(list);
// ES6
[a, ...rest] = list;
[...list] = [a, res]
console.log(list);
}
{
const [first1, ...rest1] = [1, 2, 3, 4, 5];
first1 // 1
rest1 // [2, 3, 4, 5]
const [first2, ...rest2] = [];
first2 // undefined
rest2 // []
const [first3, ...rest3] = ["foo"];
first3 // "foo"
rest3 // []
}
如果將擴充套件運算子用於陣列賦值,只能放在引數的最後一位,否則會報錯。
{
// const [...butLast, last] = [1, 2, 3, 4, 5];
// 報錯
// const [first, ...middle, last] = [1, 2, 3, 4, 5];
// 報錯
}
(4)字串
擴充套件運算子還可以將字串轉為真正的陣列。
{
console.log([...'hello']);
// [ "h", "e", "l", "l", "o" ]
}
{
let str = 'x\uD83D\uDE80y';
str.split('').reverse().join('');
// 'y\uDE80\uD83Dx'
[...str].reverse().join('');
console.log(str)
// 'y\uD83D\uDE80x'
}
上面程式碼中,如果不用擴充套件運算子,字串的reverse操作就不正確。
4.實現了 Iterator 介面的物件
任何 Iterator 介面的物件(參閱 Iterator 一章),都可以用擴充套件運算子轉為真正的陣列。
{
let nodelist = document.querySelectorAll('div');
console.log(nodelist);
console.log(...nodelist);
console.log([...nodelist]);
}
上面程式碼中,querySelectorAll方法返回的是一個NodeList物件。它不是陣列,而是一個類似陣列的物件。這時,
擴充套件運算子可以將其轉為真正的陣列,原因就在於NodeList物件實現了 Iterator
{
let arrayLike = {
'0': 'a',
'1': 'b',
'2': 'c',
length: 3
};
// TypeError: Cannot spread non-iterable object.
// let arr = [...arrayLike];
let arr = Array.from(arrayLike);
console.log(arr);
}
上面程式碼中,arrayLike是一個類似陣列的物件,但是沒有部署 Iterator 介面,擴充套件運算子就會報錯。這時,可以改為使用Array.from方法將arrayLike轉為真正的陣列。
(6)Map 和 Set 結構,Generator 函式
// 擴充套件運算子內部呼叫的是資料結構的 Iterator 介面,因此只要具有 Iterator 介面的物件,都可以使用擴充套件運算子,比如 Map 結構。