Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use the Spread operator in JavaScript

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)05/31 Report--

这篇"JavaScript中的Spread运算符怎么使用"文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇"JavaScript中的Spread运算符怎么使用"文章吧。

1.在log中使用延展操作运算符

你可以在 console.log 中对可迭代对象使用延展操作操作符

let fruits = ['?', '?', '?', '?']; console.log(...fruits); //? ? ? ?

2.用延展操作运算符复制数组

let fruits = ['?', '?', '?', '?']; let fruitsCopy = [ ...fruits ]; console.log(...fruitsCopy); //? ? ? ?

复制对象

let user = {name : "John", age : 20 } let userCopy = {...user}

延展操作运算符不执行深度复制。

3.延展操作运算符合并

let fruits = ['?', '?', '?', '?']; let vegetables = ['?', '?', '?']; let fruitsAndVeg = [...fruits, ...vegetables]

合并对象

合并对象时,如果已经存在某个键,则将其替换为具有相同键的最后一个对象。

let user1 = {name : "John", age : 20 }; let user2 = {name : "Ram", salary: '20K' }; let userCopy = {...user1, ...user2}; userCopy ; // {name : "Ram", age :20 , salary : '20K'};

4.延展操作运算符作为参数传递

function sum(a, b) { return a+b; } let num = [1,2]; sum(...num); // 3

与 math 函数一起使用

let num = [5,9,3,5,7]; Math.min(...num); Math.max(...num);

5.延展操作运算符在解构变量中

let [Melon, ...fruits ] = ['?', '?', '?', '?']; Melon; //? fruits; // [ '?', '?', '?']

解构对象

let user = {name : "Ram", age: 20, salary: '20K', job : "Tester" }; let { name, age, ...details } = user; name; // Ram age; // 20 details; // {salary: '20K', job : 'Tester'};

6.将NodeList对象转换为数组

NodeList类似于数组,但是没有 Array 的所有方法,例如 forEach,map,filter 等。

let nodeList = document.querySelectorAll('.class') var nodeArray = [...nodeList]

7.将字符串转换为字符

字符串也是可迭代的对象,因此我们也可以使用 ... 来字符串。

let name = "Ram"; let chars = [...name]; // ["R", "a", "m"]

8.从数组中删除重复项

let num = [1, 3, 1, 3, 3, 1]; let uniqueNum = [...new Set(num)]; uniqueNum; //[ 1, 3 ]以上就是关于"JavaScript中的Spread运算符怎么使用"这篇文章的内容,相信大家都有了一定的了解,希望小编分享的内容对大家有帮助,若想了解更多相关的知识内容,请关注行业资讯频道。

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report