解構(gòu)
1、數(shù)組解構(gòu)
let [a, b, c] = [1, 2, 3];
console.log(a); //1
2胎撤、對象的解構(gòu)賦值
let { foo, bar } = { foo: "aaa", bar: "bbb" };
console.log(foo); //"aaa"
3晓殊、字符串的解構(gòu)賦值
const [a, b, c, d, e] = 'hello';
a // "h"
4、數(shù)值和布爾值的解構(gòu)賦值
let {toString: s} = 123;
s === Number.prototype.toString // true
let {toString: s} = true;
s === Boolean.prototype.toString // true
5伤提、函數(shù)參數(shù)的解構(gòu)賦值
function add([x, y]){
return x + y;
}
add([1, 2]); // 3
上面代碼中巫俺,函數(shù)add的參數(shù)表面上是一個數(shù)組,但在傳入?yún)?shù)的那一刻肿男,數(shù)組參數(shù)就被解構(gòu)成變量x和y介汹。對于函數(shù)內(nèi)部的代碼來說,它們能感受到的參數(shù)就是x和y舶沛。
function move({x = 0, y = 0} = {}) {
return [x, y];
}
move({x: 3, y: 8}); // [3, 8]
move({x: 3}); // [3, 0]
move({}); // [0, 0]
move(); // [0, 0]
函數(shù)參數(shù)的解構(gòu)也可以使用默認值嘹承。
6、for循環(huán)解構(gòu)
var arr = [[11, 12], [21, 22], [31, 32]];
for (let [a, b] of arr) {
console.log(a);
console.log(b);
}
//11
//12
//21
//22
//31
//32
擴展運算符
擴展運算符(spread運算符)用三個點號(...)表示如庭,==功能是把數(shù)組或類數(shù)組對象展開成一系列用逗號隔開的值==叹卷。
let foo = function(a, b, c) {
console.log(a);
console.log(b);
console.log(c);
}
let arr = [1, 2, 3];
//傳統(tǒng)寫法
foo(arr[0], arr[1], arr[2]);
//使用擴展運算符
foo(...arr);
//1
//2
//3
特殊應(yīng)用場景:
1、數(shù)組深拷貝-數(shù)組中的元素為基本類型柱彻,若為object豪娜,依然會拷貝引用地址
var arr = [1, 2, 3];
var arr2 = arr;
var arr3 = [...arr];
console.log(arr===arr2); //true, 說明arr和arr2指向同一個數(shù)組的引用地址
console.log(arr===arr3); //false, 說明arr3和arr指向不同數(shù)組引用餐胀,在堆內(nèi)存中為arr3另外分配了內(nèi)存空間
2哟楷、把一個數(shù)組插入另一個數(shù)組字面量
var arr4 = [...arr, 4, 5, 6];
console.log(arr4);//[1, 2, 3, 4, 5, 6]
3、字符串轉(zhuǎn)數(shù)組
var str = 'love';
var arr5 = [...str];
console.log(arr5);//[ 'l', 'o', 'v', 'e' ]
4否灾、函數(shù)調(diào)用
function push(array, ...items) {
array.push(...items)
}
function add(x, y) {
return x + y
}
const numbers = [4, 38]
add(...numbers) // 42
5卖擅、替代數(shù)組的 apply 方法
由于擴展運算符可以展開數(shù)組,所以不再需要apply方法,將數(shù)組轉(zhuǎn)為函數(shù)的參數(shù)了惩阶。
// ES5 的寫法
function f(x, y, z) {
// ...
}
var args = [0, 1, 2];
f.apply(null, args);
// ES6 的寫法
function f(x, y, z) {
// ...
}
var args = [0, 1, 2];
f(...args);
另一個例子是通過push函數(shù)挎狸,將一個數(shù)組添加到另一個數(shù)組的尾部。
// ES5 的寫法
var arr1 = [0, 1, 2];
var arr2 = [3, 4, 5];
Array.prototype.push.apply(arr1, arr2);
// ES6 的寫法
var arr1 = [0, 1, 2];
var arr2 = [3, 4, 5];
arr1.push(...arr2)
rest運算符
rest運算符也是三個點號断楷,不過其功能與擴展運算符恰好相反锨匆,把逗號隔開的值序列組合成一個數(shù)組。
//主要用于不定參數(shù)冬筒,所以ES6開始可以不再使用arguments對象
var bar = function(...args) {
for (let el of args) {
console.log(el);
}
}
bar(1, 2, 3, 4);
//1
//2
//3
//4
bar = function(a, ...args) {
console.log(a);
console.log(args);
}
bar(1, 2, 3, 4);
//1
//[ 2, 3, 4 ]
rest運算符配合解構(gòu)使用:
// 數(shù)組
const [a, ...rest] = [1, 2, 3, 4];
console.log(a);//1
console.log(rest);//[2, 3, 4]
// 對象配合
const {age, ...rest} = {name: 'qxj', age: 24, hobby: 'write code'};
console.log(age); //24
console.log(rest); //{ name: 'qxj', hobby: 'write code' }
rest運算符和spread運算符的區(qū)別:
spread運算符:放在賦值一方恐锣,即放在實參或者等號右邊
rest運算符:放在被賦值一方,即放在形參或者等號左邊