spread_通过Rest and Spread实现JavaScript的现代化

spread

Exploring two recent features that will make your code cleaner and more robust

探索两项最新功能,这些功能将使您的代码更简洁,更健壮

The Rest and Spread operators were introduced in ES6 (2015) and further extended in ES9 (2018). In this article, I will explain what these operators do and provide some practical use-cases for modernizing your code.

Rest和Spread运算符在ES6 (2015)中引入,并在ES9(2018)中进一步扩展。 在本文中,我将解释这些运算符的作用,并提供一些实用的用例来使代码现代化。

休息 (Rest)

JavaScript’s rest parameter is a way of passing a variable number of arguments to a function in a single parameter.

JavaScript的rest参数是一种通过单个参数将可变数量的参数传递给函数的方法。

The basic syntax uses three dots before the parameter name, and can be used as follows:

基本语法在参数名称前使用三个点,可以按如下方式使用:

function f(x, ...args) {
console.log(args instanceof Array); // -> true
console.log(args.length); // -> 3
console.log(args[0]); // -> 2
console.log(args[1]); // -> Hello
}f(1, 2, 'Hello', 3);

The semantics of the ... could be conceptualized as ‘the rest of the parameters’. Note that default values are not allowed for the rest parameter, so we cannot write ...args = 1,2,3.

的语义...可以概括为“的其余参数”。 请注意, rest参数不允许使用默认值,因此我们无法编写...args = 1,2,3

传播 (Spread)

The spread operator could be thought of as the inverse of the rest parameter.

扩频算子可以被认为是rest参数的倒数。

Rather than packing multiple arguments into a single parameter, the spread operator unpacks a collection into individual values. From ES9 onwards, the spread operator works on objects, arrays, and strings and can be used as follows:

散布运算符不是将多个参数打包到单个参数中,而是将集合拆包成单个值。 从ES9开始,spread运算符可处理对象,数组和字符串,并且可以按以下方式使用:

function f(...args) {
console.log(args); // -> [1, 2, "Hello", 3]
}const myargs = [1, 2, 'Hello', 3];
f(...myargs);

The semantics of the ... in the spread operator could be conceptualized as ‘spread across multiple variables’. So, in the above example, the elements of the array myargs are spread across four input parameters consumed by the function f().

传播运算符中 ...的语义可以概念化为“ 多个变量传播 ”。 因此,在上面的示例中,数组myargs的元素分布在函数f()使用的四个输入参数上。

应用领域 (Applications)

The spread operator is a particularly powerful tool in modernizing JavaScript code. Here are some practical applications:

传播算子是使JavaScript代码现代化的特别强大的工具。 以下是一些实际应用:

Concatenate Arrays

串联数组

const a = [1,2,3];
const b = [4,5,6];
const c = [...a, ...b]; // Spread a and b across array init
console.log(c); // -> [1, 2, 3, 4, 5, 6]

Modify or Add Object Properties

修改或添加对象属性

const a = { x: 1, y: 2 }
const b = { ...a, x: 3 } // Replace x property
console.log(b); // -> { x: 3, y: 2 }const c = { ...b, z: 4 } // Add z property
console.log(c); // -> { x: 3, y: 2, z: 4 }

Convert String to Array

将字符串转换为数组

const s = "Hello";
const a = [...s];
console.log(a); // -> ["H", "e", "l", "l", "o"]

结合休息和破坏性分配 (Combining Rest and Destructuring Assignment)

Destructuring assignment is another language feature that was introduced in ES6. For example, we can write

销毁结构分配是ES6中引入的另一种语言功能。 例如,我们可以写

const a = [1, 2];
const [b, c] = a; // Destructure the elements of a into b and c
console.log(b) // -> 1
console.log(c) // -> 2const obj = { x: 1, y: 2, z: 3 };
const {x, y, z} = obj; // Destructure property values of obj
console.log(x); // -> 1

This becomes incredibly powerful when combined with rest elements, or rest properties. In the context of destructuring the assignment, the ... syntax has the same semantics as in rest parameters, meaning “the rest of” the elements or “the rest of” the properties.

rest元素rest属性结合使用时,这将变得异常强大。 在解构分配的上下文中, ...语法与其余参数具有相同的语义,即元素的“其余”或属性的“其余”。

Some examples:

一些例子:

Remove a Property from an Object

从对象中删除属性

const a = { x: 1, y: 2, z: 3 };
const {x, ...b} = a; // Destructure a into x and b
console.log(x); // -> 1
console.log(b); // -> {y: 2, z: 3}

Set a Default Value for a Destructured Variable

为解构变量设置默认值

const b = { x: 1, y: 2 };const {z: z = 0, ...c} = a;   // assign zero to z if not present
console.log(c); // -> {x: 1, y: 2}
console.log(z); // -> 0

Even more advanced uses of rest and spread with destructuring can be found in this post.

可以在这篇文章中找到对休息和分散传播的更高级使用。

注意事项 (Caveats)

The spread operator performs a clone of the elements in the object being spread, but it is only a shallow clone. So any nested objects will refer to their original instances. For example:

传播算子对正在传播的对象中的元素执行克隆,但这只是一个浅表克隆。 因此,任何嵌套对象都将引用其原始实例。 例如:

let q = [1,2];
const a = [q, 3];
const [b, c] = a;q[0] = 5;console.log(b); // Expected 1 (deep clone), but got 5 (shallow)

支持的浏览器 (Supported Browsers)

Despite being introduced several years ago, some of these features are not supported by default in all modern browsers. You should check on caniuse.com before using this functionality in your code, or alternatively use an intermediate compiler like Babel to ensure compatibility.

尽管几年前才引入这些功能,但并非所有现代浏览器默认都支持其中一些功能。 在代码中使用此功能之前,应先检查caniuse.com ,或者使用Babel这样的中间编译器来确保兼容性。

Thank you for reading. If you have any interesting applications of rest and spread, I’d love to hear them in the comments.

感谢您的阅读。 如果您对休息和传播有任何有趣的应用,我很乐意在评论中听到它们。

翻译自: https://codeburst.io/modernize-your-javascript-with-rest-and-spread-fb3b97fba5db

spread

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值