ES6之扩展运算符


扩展运算符(spread)是三个点( ...), 将一个数组转为用逗号分隔的参数序列

console.log(...[1, 2, 3]); // 1 2 3
console.log(1, ...[2, 3, 4], 5); // 1 2 3 4 5
console.log([...document.querySelectorAll('div')]);  // [<div>, <div>, <div>]

数组克隆

const arr = [1, 2, 3, 4];
const arr1 = [...arr];

console.log(arr1); // [1, 2, 3, 4]

数组合并

const arr1 = [1, 2, 3, 4];
const arr2 = [5, 6];
const arr3 = [7, 8];
const arr4 = [...arr1, ...arr2, ...arr3];
// 等价于
const arr4 = arr1.concat(arr2, arr3);

console.log(arr4); // [1, 2, 3, 4, 5, 6, 7, 8]
let a = [14,12,54,33,22];
let b = a;  // b是a的一个引用,也就是说二者所在的内存是同一个
a.push(44);

console.log(a); // [14, 12, 54, 33, 22, 44]
console.log(b); // [14, 12, 54, 33, 22, 44]

要想改变a不影响b的话,就要开辟一个新内存,解决方式:

let a = [14,12,54,33,22];
let b = [...a];
a.push(44);

console.log(a); // [14, 12, 54, 33, 22, 44]
console.log(b); // [14, 12, 54, 33, 22]

数组拼接

const arr1 = [1, 2, 3, 4];
const arr2 = [5, 6];
arr1.push(...arr2);

console.log(arr1); // [1, 2, 3, 4, 5, 6]

字符串转数组

var str = "hello js";

console.log([...str]); //["h", "e", "l", "l", "o", " ", "j", "s"]
// 等价于
console.log(str.split('')); //["h", "e", "l", "l", "o", " ", "j", "s"]

与解构赋值结合

扩展运算符可以与解构赋值结合起来,用于生成数组

const [first, ...rest] = [1, 2, 3, 4, 5];
console.log(first, rest) //1  [2, 3, 4, 5]
const [first, ...rest] = [1];
console.log(first, rest) //1  []

如果将扩展运算符用于数组赋值,只能放在参数的最后一位,否则会报错(Rest element must be last element)

const [...rest, first] = [1, 2, 3, 4, 5]; //  报错
const [first, ...rest, last] = [1, 2, 3, 4, 5]; //  报错

类数组转换成真正的数组

var div = document.querySelectorAll('div'); // 获得一个类数组 NodeList

var arr1 = [...div] ;  // 类数组转换成真正的数组
// 等价于
var arr2 = Array.from(div) ;

剩余参数

const arr = [1, 2, 3, 4];

function fn(i, ...arguments) {
    console.log(i); // 1
    console.log(arguments); // [2, 3, 4]
}

fn(...arr);
posted @ 2022-07-20 18:15  猫老板的豆  阅读(155)  评论(0编辑  收藏  举报