JavaScript — 使用扩展运算符 (...)
简述如何在 JavaScript 中使用展开运算符 (...)
介绍
在 MDN Web Docs 上,它说“扩展语法 (...)
允许在预期零个或多个参数(用于函数调用)或元素(用于数组文字)的地方扩展诸如数组表达式或字符串之类的迭代,或者 在需要零个或多个键值对(对于对象字面量)的地方扩展对象表达式。”
这是很多复杂东西,对吧? 好吧,我会试着为大家总结一下。 希望在本文结束时,大家会知道如何使用扩展运算符。
如何使用展开运算符 ...
可以通过三种不同的方式使用扩展运算符:
- 对于函数调用
- 对于一个数组
- 对于一个对象
尽管大家最常在对象或数组中使用它,但了解如何在函数调用中使用它仍然很有用。 我将在下面详细介绍其中的每一个。
函数调用中
顾名思义,“spread”运算符将值展开。 在调用函数时使用扩展运算符的情况下,我们将其称为 myFunction(...args)
。 在函数体中,我们可以将 args 变量用作常规数组,将数组中的每个元素作为输入的参数之一。
const sum = (...nums) => {
// `nums` can be thought of as [1,2,3,4,5]
let total = 0;
for (let i=0; i < nums.length; i++) {
total = total + nums[i];
}
return total;
}
sum(1); // 1
sum(1,2,3); // 6
sum(1,2,3,4,5); //15
对于一个数组
扩展运算符也可用于数组。 同样,顾名思义,它将值展开。 我们可以在数组中使用此扩展运算符来连接数组和深拷贝数组。 我将向大家展示如何完成这两项任务。
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const arr3 = [...arr1, 'hello'];
const arr4 = ['hello', ...arr2];
const arr5 = [...arr1, ...arr2];
const arr6 = [...arr1, arr2];
console.log(arr3);
console.log(arr4);
console.log(arr5);
console.log(arr6);
对于一个对象
扩展运算符也可用于对象。 再一次,顾名思义,它将值展开。 可以使用扩展运算符合并对象,就像数组一样。 除此之外,扩展运算符可用于更新对象内的属性。
const obj1 = {1:'a', 2:'b'}
const obj2 = {3:'c', 4:'d'}
const obj3 = {...obj1, ...obj2}
console.log(obj3);
const obj1 = {1: 'old a', 2:'old b'}
const obj2 = {2: 'new b'}
const obj3 = {...obj1, ...obj2}
console.log(obj3);
总结
扩展运算符可以以各种方式使用,我强烈建议各位看官熟悉它。 扩展运算符本质上是语法糖,但如果使用得当,它可以让你的代码更简洁,增强可读性。 相信我,花大约 30 分钟在谷歌上搜索扩展运算符,你会感谢我的。
希望这篇文章能帮助各位理解展开运算符 (...)
。 如果各位认为我误解了某些内容,请告诉我,我将对文章进行必要的更改。 谢谢!
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
如何在 JavaScript 中合并两个数组而不出现重复的情况
发布时间:2024/03/23 浏览次数:86 分类:JavaScript
-
本教程介绍了如何在 JavaScript 中合并两个数组,以及如何删除任何重复的数组。