扩展运算符
扩展运算符(spread)也是三个点(…)。它好比 rest 参数的逆运算,将一个数组转为用逗号分隔的参数序列,对数组进行解包
1.展开数组:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| const fruits = ["apple", "banana", "grapes"]; console.log(fruits);
console.log(...fruits);
function test1(p1, p2) { console.log(arguments); console.log(p1); console.log(p2); } test1(...fruits);
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title></title> </head> <body> <div></div> <div></div> <div></div> <script> 1.数组的合并 const fruits = ["apple", "banana"]; const lang = ["Java", "Go"]; const combine1 = fruits.concat(lang); console.log(combine1); const combine2 = [...fruits, ...lang]; console.log(combine2);
const letter = ["A", "B", "C"]; const copy = [...letter]; console.log(copy);
const divs = document.querySelectorAll("div"); const divArray = [...divs]; console.log(divs); console.log(divArray); </script> </body> </html>
|
2.展开对象
1 2 3 4 5 6 7 8 9 10 11 12 13
| const info = { id: 1, name: "xiaoming", age: 10 }; const score = { math: 90, physics: 80, music: 95 }; const stuObj = {...info, ...score}; console.log(stuObj);
|