01-剩余运算符 …
<script>
// 剩余运算:...,获取剩余的数据
let hero = {
name: '德莱厄斯',
age: 18,
gender: '小C',
skill: [
{
skill1: '自残打击'
},
{
skill2: '大杀四方'
},
{
skill3: '无情铁手'
}
]
}
// 需求:解构hero中的数据,skill单独取出来,其他的方法一起
const { skill, ...others } = hero
console.log(skill, others)
// 将其他的内容(剩余的内容)放到一个变量里面
// 如果原来是对象:产生的就是对象;如果原来是数组,产生的就是数组
// 剩余运算的其他应用
// 1. 获取多余的实参(使用较多)
function max(first, ...others) {
// 安全思想:保证代码一定能得到正确的结果
if (first == undefined) return false
// 判定first是不是一个数字
if (isNaN(first)) return false
// 第一个实参给first赋值
// 其他的都给others:others是一个数组
// console.log(first, others)
// others比arguments好
// 1. arguments不管有没有形参:获取所有实参
// 2. arguments是伪数组:数组API不能用,others是数组:所有的数组API都可以使用
let max = first
// others.forEach((item) => {
for (let i = 0; i < others.length; i++) {
// 添加一个判定
if (parseFloat(others[i]) != others[i]) return false
if (others[i] > max) max = others[i]
}
// })
return max
}
max(1)
max(1, 2, 3, 4, 5)
// 2. 可以给实参用:名字叫做打散(可以打散数组)
let ages = [18, 20, 30, 40, 14, 60]
// 求ages的最大值
// max(ages)
// 打散数组(用于实参)
max(...ages) // === max(18, 20, 30, 40, 14, 60)
function log() {
console.log.call(console, ...arguments)
}
log(1, 2, 3, 4, 5, 6)
</script>
注意:
1. // 将其他的内容(剩余的内容)放到一个变量里面
// 如果原来是对象:产生的就是对象;如果原来是数组,产生的就是数组
2. // others比arguments好
// 1. arguments不管有没有形参:获取所有实参
// 2. arguments是伪数组:数组API不能用,others是数组:所有的数组API都可以使用
3.可以给实参用:名字叫做打散(可以打散数组)