<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ES6--扩展运算符(...)和rest运算符</title>
</head>
<body>
<script>
/*
ES6--扩展运算符(...)和rest运算符
*/
/*
1.扩展运算符(...)
1.1 扩展运算符
1.2 运用
2.rest运算符
2.1 rest运算符
2.2 运用
*/
// 1.扩展运算符(...)
// 1.1 扩展运算符
/*
扩展运算符(...)用于将一个数组或类数组对象转换为逗号分隔的值序列。
它的基本用法是拆散数组和字符串。
*/
const arr=[1,2,3,4,5,6];
console.log(...arr);//1 2 3 4 5 6
const str='string';
console.log(...str);//s t r i n g
// 1.2 运用
// 1.2.1 替代apply()函数
/*
原:
let arr=[1,2,3,4,5,6];
console.log(Math.max.apply(null,arr));//6
*/
console.log(Math.max(...arr));//6
// 1.2.2 替代concat()函数合并数组
/*
原:let arr1=[1,2,3];
let arr2=[4,5,6];
console.log(arr1.concat(arr2));
*/
let arr1=[1,2,3];
let arr2=[4,5,6];
console.log([...arr1,...arr2]);//[1, 2, 3, 4, 5, 6]
//...
// 2.rest运算符
// 2.1 rest运算符
/*
rest运算符(...)同样用3个点表示,其作用与扩展运算符相反,
用于将以逗号分隔的值序列转换为数组。
*/
// 2.2 运用
//2.2.1 rest运算符与解构组合使用
let arr3=['a','b','c','d'];
let [arg1,...arg2]=arr3;
console.log(arg1);//a
console.log(arg2);//['b', 'c', 'd']
//2.2.2 rest运算符代替arguments处理函数参数
/*
function foo(){
for(let arg of arguments){
console.log(arg);
}
}
foo('a','b','c','d');//a b c d
*/
function foo(...args){
for(let arg of args){
console.log(arg);
}
}
foo('a','b','c','d');//a b c d
// ...
</script>
</body>
</html>