ES6教程

ES6 扩展运算符

ES6 扩展运算符

ES6 引入了一种称为扩展的新运算符运算符,由三个点(...) 组成。它允许可迭代对象在预期参数超过零的地方进行扩展。它给了我们从数组中获取参数的特权。
Spread 运算符的语法与 rest 参数类似,但完全相反。让我们了解展开运算符的语法。

语法

var variablename1 = [...value];
以上语法中的三个点(...) 是扩展运算符,它针对特定变量中的整个值。
让我们尝试了解扩展运算符在不同案例:

扩展运算符和数组操作

在这里,我们将看到如何使用扩展运算符来操作数组。

构造数组字面量

当我们使用字面量形式构造数组时,展开运算符允许我们在已初始化的数组中插入另一个数组。
示例
let colors = ['Red', 'Yellow'];
let newColors = [...colors, 'Violet', 'Orange', 'Green'];
console.log(newColors);
输出
[ 'Red', 'Yellow', 'Violet', 'Orange', 'Green' ]

连接数组

扩展运算符也可用于连接两个或多个数组。
示例
let colors = ['Red', 'Yellow'];
let newColors = [...colors, 'Violet', 'Orange', 'Green'];
console.log(newColors);
输出
[ 'Red', 'Yellow', 'Violet', 'Orange', 'Green' ]

复制数组

我们也可以使用展开运算符复制数组的实例。
示例
let colors = ['Red', 'Yellow'];
let newColors = [...colors];
console.log(newColors);
输出
[ 'Red', 'Yellow' ]
如果我们不使用扩展运算符复制数组元素,那么在复制的数组中插入新元素会影响原始数组。
但如果我们使用扩展运算符复制数组,那么在复制的数组中插入一个元素不会影响到原来的数组。
我们来理解一下这个例子。
例子
不使用扩展运算符
let colors = ['Red', 'Yellow'];
let newColors = colors;
newColors.push('Green');
console.log(newColors);
console.log(colors);
输出
[ 'Red', 'Yellow', 'Green' ]
[ 'Red', 'Yellow', 'Green' ]
使用扩展运算符
let colors = ['Red', 'Yellow'];
let newColors = [...colors];
newColors.push('Green');
console.log(newColors);
console.log(colors);
输出
[ 'Red', 'Yellow', 'Green' ]
[ 'Red', 'Yellow' ]
注意: 展开运算符只将数组本身复制到新数组,而不是元素。这意味着操作员可以做浅拷贝而不是深拷贝。

展开运算符和字符串

让我们看看展开运算符如何展开字符串。下面给出了相同的说明。
示例
在这里,我们从单个字符串构造了一个数组 str。
let str = ['A', ...'EIO', 'U'];
console.log(str);
在上面的示例中,我们将扩展运算符应用于字符串'EIO'。它将'EIO'字符串的每个特定字符展开成单个字符。
执行上述代码后,我们将得到以下输出。
输出
[ 'A', 'E', 'I', 'O', 'U' ]
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4