spread运算符_JavaScript中的Spread运算符有什么用?

spread运算符

Learn about the ES6 spread operator, and some practical uses for this powerful JavaScript feature!

了解ES6传播运算符,以及此强大JavaScript功能的一些实际用法!

The spread operator is a feature of JavaScript introduced with ES6 that gives you access to the insides of an iterable object. The term “iterable object” is really just a computer science-y term for a category of data types. Specifically: arrays, objects literals, and strings.

传播运算符是ES6引入JavaScript的一项功能, 使您可以访问可迭代对象的内部 。 术语“可迭代对象”实际上只是一类计算机科学术语,代表一类数据类型。 具体来说:数组,对象文字和字符串。

What makes them “iterable”? These kinds of JavaScript types can be traversed in some sequential fashion. For example, you can use a for loop on an array, or with object literals you can use for…in loops.

是什么使它们“可迭代”? 可以以某种顺序方式遍历这些类型JavaScript。 例如,可以在数组上使用for循环 ,也可以在对象常量中使用for ... in循环

The spread operator effectively gives you access to the “stuff” inside these iterable objects. Let’s look an example to illustrate what that means:

传播算子有效地使您可以访问这些可迭代对象内部的“填充”。 让我们看一个例子来说明这意味着什么:

const foo = [
  'hello',
  'bonjour',
  'konnichiwa'
];
const bar = [...foo]; // the three dots "..." are the spread operator syntax!

console.log(bar);
// ['hello', 'bonjour', 'konnichiwa'];

The variable bar got an exact copy from foo! Whoa…

变量barfoo得到了一个精确的副本! 哇...

const foo = [
  <^>'hello',
  'bonjour',
  'konnichiwa'<^>
]
const bar = [...foo]

The spread operator essentially scooped out the insides of the foo array and spread the values across the new array in bar.

散布运算符本质上是挖出foo数组的内部并将值分布在bar的新数组中。



Now that we have a basic idea, let’s look at common tasks where the spread operator might be useful.

现在我们有了一个基本概念,让我们看一下散布运算符可能有用的常见任务。

复制可迭代对象 (Duplicating Iterable Objects)

As we saw earlier, the spread operator is one of the best ways for duplicating an iterable object. There are more complex ways to do this, but the conciseness of the spread operator makes it delightfully easy.

正如我们前面所看到的,散布运算符是复制可迭代对象的最佳方法之一。 有许多更复杂的方法可以执行此操作,但由于传播操作符的简洁性,操作起来非常轻松。

const foo = ['hello', 'bonjour', 'konnichiwa'];
const bar = ...foo; // uh-oh :<

Kinda pulled a sneaky on ya. You have to drop it into a new set of brackets in bar! 😬

金达偷偷摸摸地看着你。 您必须将其放入bar一组新括号中! 😬

const foo = ['hello', 'bonjour', 'konnichiwa'];
const bar = [...foo]; // woohoo! :>

console.log(bar);
// ['hello', 'bonjour', 'konnichiwa']

Using the spread operator to duplicate object literals isn’t much different than arrays. Just remember to BYOB (bring your own brackets):

使用散布运算符复制对象文字与数组没有太大不同。 请记住要使用BYOB(自带括号):

const foo = {
  english: 'hello',
  french: 'bonjour',
  japanese: 'konnichiwa'
};
const bar = {...foo};

console.log(bar);
// { english: 'hello', french: 'bonjour', japanese: 'konnichiwa' }

合并可迭代对象 (Merging Iterable Objects)

The spread operator can also be used to compose a single value from several other values!

传播算子还可以用于从多个其他值组成一个值!

const foo = ['hello', 'bonjour', 'konnichiwa'];
const bar = ['gutentag', 'hello-ey'];
const baz = [...foo, ...bar];

console.log(baz);
// ['hello', 'bonjour', 'konnichiwa', 'gutentag', 'hello-ey']

Now baz is the merged value of both foo and bar. You can also place the spreaded array inside another array:

现在bazfoobar的合并值。 您还可以将散布的数组放置在另一个数组中:

const foo = ['hello', 'bonjour', 'konnichiwa'];
const bar = [...foo, 'gutentag', 'hello-ey'];

console.log(bar);
// ['hello', 'bonjour', 'konnichiwa', 'gutentag', 'hello-ey']

This is where your well-trained JavaScript instincts might think this looks really weird… But remember that the spread operator just holds the “stuff”. Where you put that “stuff” is up to you! 💫

在这里,您训练有素JavaScript本能可能认为这看起来很奇怪……但是请记住,散布运算符只是保留“东西”。 您将“内容”放置在哪里取决于您! 💫

How about object literals? It’s very similar to merging arrays:

对象文字如何呢? 这与合并数组非常相似:

const foo = {
  english: 'hello',
  french: 'bonjour',
  japanese: 'konnichiwa'
};
const bar = {
  german: 'gutentag',
  canadian: 'hello-ey'
};
const baz = {...foo, ...bar};

console.log(baz);
// { english: 'hello', french: 'bonjour', japanese: 'konnichiwa', german: 'gutentag', canadian: 'hello-ey' }

Boom! This used to be a task for Object.assign() but the spread syntax makes this far more concise.

繁荣! 这曾经是Object.assign()的任务,但是传播语法使这一过程更加简洁。

What happens when there’s duplicate keys?

重复的密钥会发生什么?

const foo = {
  english: 'hello',
  french: 'bonjour',
  japanese: 'konnichiwa'
};
const bar = {
  english: 'howdy',
  german: 'gutentag'
};
const baz = {
  ...foo,
  ...bar,
  canadian: 'hello-ey',
  korean: 'annyeong'
};

console.log(baz);
// { english: 'howdy', french: 'bonjour', japanese: 'konnichiwa', german: 'gutentag', canadian: 'hello-ey', korean: 'annyeong' }

The duplicate keys are overwritten!

重复的密钥将被覆盖!

Remember that the ellipses go in front of the variable not after: ...myVariable not myVariable...

请记住,省略号不在变量之后 : ...myVariable不是myVariable...

将参数输入函数 (Feeding Arguments into Functions)

You may encounter this less often, but you can also use the spread operator for feeding arguments into a function.

您可能很少遇到这种情况,但是您也可以使用Spread运算符将参数提供给函数。

const cube = [12, 30, 14];

function calcVolume(width, height, depth) {
  return width * height * depth;
};

calcVolume(12, 30, 14);         // basic
calcVolume.apply(null, cube);   // using "apply"
calcVolume(...cube);          // using "spread operator"

The spread operator makes it incredibly easy to feed a series of arguments into functions.

扩展运算符使将一系列参数输入函数变得异常容易。

你说过一些关于弦的事 (You Said Something About Strings)

Lastly, you can also use the spread operator with strings since they’re also considered an iterable object (it has slice, and length functions!)

最后,您还可以对字符串使用spread运算符,因为它们也被视为可迭代对象(它具有slicelength函数!)

const foo = "jumanji";
const bar = [...foo];

console.log(bar);
// [ "j", "u", "m", "a", "n", "j", "i" ]

You may not encounter a need to use the spread operator for strings unless you develop software for natural language processing, or some kinda machine learning. I’m not sure… But it definitely works on strings!

除非您开发用于自然语言处理或某种机器学习的软件,否则可能不需要对字符串使用扩展运算符。 我不确定...但是它肯定可以在字符串上工作!

结论 (Conclusion)

The spread operator was a highly requested feature that was already available in old-school languages like C++ and Python, and now it’s here! It makes some common programming tasks really easy to do, and hopefully you learned practical ways you could use it!

传播运算符是一项非常受人欢迎的功能,该功能已在C ++和Python等老式语言中提供,现在就在这里! 它使一些常见的编程任务真的很容易实现,并且希望您学习了可以使用它的实用方法!

See MDN for in-depth documentation on the spread operator.

有关传播操作符的深入文档,请参阅MDN

翻译自: https://www.digitalocean.com/community/tutorials/js-spread-operator

spread运算符

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
拓展运算符spread operator)在JavaScript用三个连续的点(...)表示。它可以在函数调用、数组字面量和对象字面量使用,用于展开可迭代对象(如数组、字符串、Map、Set等)。 在函数调用,拓展运算符可以将一个数组展开为独立的参数传递给函数。例如: ```javascript function add(a, b, c) { return a + b + c; } const numbers = [1, 2, 3]; console.log(add(...numbers)); // 输出:6 ``` 在数组字面量,拓展运算符可以将一个数组的元素展开到另一个数组。例如: ```javascript const arr1 = [1, 2, 3]; const arr2 = [...arr1, 4, 5, 6]; console.log(arr2); // 输出:[1, 2, 3, 4, 5, 6] ``` 在对象字面量,拓展运算符可以将一个对象的属性展开到另一个对象。如果有相同的属性名,则后面的属性值会覆盖前面的。例如: ```javascript const obj1 = { a: 1, b: 2 }; const obj2 = { ...obj1, c: 3 }; console.log(obj2); // 输出:{ a: 1, b: 2, c: 3 } ``` 拓展运算符还可以用于克隆数组和对象,因为它创建了一个新的数组或对象副本。例如: ```javascript const originalArray = [1, 2, 3]; const newArray = [...originalArray]; console.log(newArray); // 输出:[1, 2, 3] const originalObject = { a: 1, b: 2 }; const newObject = { ...originalObject }; console.log(newObject); // 输出:{ a: 1, b: 2 } ``` 拓展运算符的应用还有很多,它可以简化代码并提高可读性。希望这个解答对你有帮助!如果你还有其他问题,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值