剩余运算符
通过 ...
符号来获取剩下的参数
<!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>剩余运算</title>
</head>
<body></body>
<script>
// 剩余运算: 将剩下的数据放到一个变量中
// 1. 用于收集多余的形参(不确定参数的地方): 使用最多的地方(实际使用还是很少)
function max(first, ...others) {
console.log(first, others); // others始终是数组: 哪怕没有数据
// 剩余运算得到的others数组 与 arguments有何区别?
// console.log(arguments)
// others是数组, arguments是伪数组
// others可以调用数组的任意API, arguments一个都不能调用
let m = first; // 默认第一个最大
// 遍历数组: PK
others.forEach((item) => {
if (item > m) m = item;
});
console.log(m);
}
max(1);
max(1, 2, 3);
// 2. 用于 解构(不用)
let arr = "abcdefg".split("");
let obj = { a: "apple", b: "banana", p: "pitch" };
let [a, b, ...c] = arr; // 取出第一个和第二个,剩下的都放到c中
console.log(a, b, c);
let { p, ...t } = obj; // 取出p放到p变量, 剩下都放t中: 是对象
console.log(p, t);
// 3. 打散功能: 用于数组实参( 将数组 变成顺序的参数)
let res = Math.max(1, 2, 3, 54, 5, 6, 7, 78);
console.log(res);
arr = [1, 2, 3, 54, 5, 6, 7, 78];
// 求数组最大值
// res = Math.max(arr) // 系统将数组解析成数字: NaN
res = Math.max(...arr); // ...arr 将arr的结果变成 1, 2, 3, 54, 5, 6, 7, 78
// Math.max(1, 2, 3, 54, 5, 6, 7, 78)
console.log(res);
// 总结
// 剩余运算: 一般是给数组用 一个是怎么变成数组(收集剩余的参数: 形参) 和 打散功能( 将数组变成带顺序的 数据 : 实参)
</script>
</html>