首页 > 其他分享 >#yyds干货盘点#ES6的扩展运算

#yyds干货盘点#ES6的扩展运算

时间:2022-10-24 22:35:52浏览次数:52  
标签:yyds const arr1 ... rest 干货 ES6 数组 first

ES6通过扩展元素符​​...​​,好比 ​​rest​​ 参数的逆运算,将一个数组转为用逗号分隔的参数序列:

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

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

[...document.querySelectorAll('div')]
// [<div>, <div>, <div>]

主要用于函数调用的时候,将一个数组变为参数序列

function push(array, ...items) {
array.push(...items)
}
function add(x, y) {
return x + y
}
const numbers = [4, 38]
add(...numbers) // 42

可以将某些数据结构转为数组

[...document.querySelectorAll('div')]

能够更简单实现数组复制

const a1 = [1, 2]; 
const [...a2] = a1; // [1,2]

数组的合并也更为简洁了

const arr1 = ['a', 'b']
const arr2 = ['c']
const arr3 = ['d', 'e']
;[...arr1, ...arr2, ...arr3] // [ 'a', 'b', 'c', 'd', 'e' ]
复制代码

注意:通过扩展运算符实现的是浅拷贝,修改了引用指向的值,会同步反映到新数组

下面看个例子就清楚多了

const arr1 = ['a', 'b', [1, 2]];
const arr2 = ['c'];
const arr3 = [...arr1, ...arr2]
arr[1][0] = 9999 // 修改arr1里面数组成员值 console.log(arr[3]) // 影响到arr3,['a','b',[9999,2],'c']

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

const [first, ...rest] = [1, 2, 3, 4, 5]
first // 1
rest // [2, 3, 4, 5]

const [first, ...rest] = [];
first // undefined
rest // []

const [first, ...rest] = ["foo"];
first// "foo"
rest // []

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

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

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

const [first, middle, ...last] = [1, 2, 3, 4, 5]; // 正常运行

可以将字符串转为真正的数组

[...'hello'] // [ "h", "e", "l", "l", "o" ]

标签:yyds,const,arr1,...,rest,干货,ES6,数组,first
From: https://blog.51cto.com/u_11365839/5791478

相关文章