263 扩展运算符...(展开语法)
扩展运算符可以将 数组 或者 对象 转为用逗号分隔的参数序列。
let ary = [1, 2, 3];
...ary // 1, 2, 3
console.log(...ary); // 1 2 3,相当于下面的代码
console.log(1,2,3);
let obj = {aa: 11, bb: 22, cc: 33}
let obj2 = {dd: 44}
console.log({...obj, ...obj2}) // {aa: 11, bb: 22, cc: 33, dd: 44}
扩展运算符可以应用于合并数组
// 方法一
let ary1 = [1, 2, 3];
let ary2 = [3, 4, 5];
let ary3 = [...ary1, ...ary2];
// 方法二
ary1.push(...ary2);
console.log(arr1);
将类 数组 或 可遍历对象 转换为 真正的数组
let oDivs = document.getElementsByTagName('div');
oDivs = [...oDivs];
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>扩展运算符</title>
</head>
<body>
<div>1</div>
<div>4</div>
<div>3</div>
<div>6</div>
<div>2</div>
<div>5</div>
<script type="text/javascript">
// 扩展运算符可以将数组拆分成以逗号分隔的参数序列
let ary = ["a", "b", "c"];
// ...ary; // "a", "b", "c"
console.log(...ary); // a b c
console.log("a", "b", "c"); // a b c
// 扩展运算符应用于数组合并
let ary1 = [1, 2, 3];
let ary2 = [4, 5, 6];
// ...ary1 // 1, 2, 3
// ...ary1 // 4, 5, 6
let ary3 = [...ary1, ...ary2];
console.log(ary3); // [1, 2, 3, 4, 5, 6]
// 合并数组的第二种方法
let ary11 = [1, 2, 3];
let ary22 = [4, 5, 6];
ary11.push(...ary22);
console.log(ary11); // [1, 2, 3, 4, 5, 6]
// 利用扩展运算符将伪数组转换为真正的数组
var oDivs = document.getElementsByTagName('div');
console.log(oDivs); // HTMLCollection(6) [div, div, div, div, div, div]
var ary33 = [...oDivs];
ary33.push('a');
console.log(ary33); // [div, div, div, div, div, div, "a"]
</script>
</body>
</html>