参数扩展/展开

本文详细介绍了JavaScript中的剩余参数(`...args`)和展开语法(`...`),包括它们在函数参数、数组合并、默认值等方面的应用。通过实例展示了如何利用这些特性进行参数收集、数组操作以及函数调用。同时,还讨论了对象展开和对象的合并、解构赋值等高级用法,揭示了它们在实际开发中的强大功能。
摘要由CSDN通过智能技术生成
  • 参数扩展/展开 ...args
    • 收集剩余的参数,必须当到最后一个参数位置
    • 展开数组,简写,效果和直接把数组的内容写在这儿一样
  • 默认参数
function show (a, b, ...args) {
  console.log(a);
  console.log(b);
  console.log(args);
}
show(12, 15, 18, 20, 22, 60);

function show1 (a, b = 5, c = 12) {  // 默认参数 如果不传入参数 将使用默认值
  console.log(a, b, c);
}
show1(99);
show1(99, 19, 88);

let arr = [1, 2, 3];
// ...arr
// 1, 2, 3
function show2 (a, b, c) {
  console.log(a);
  console.log(b);
  console.log(c);
}
show2(...arr);

function show3 (...args) {
  fn(...args)
}
function fn (a, b) {
  console.log(a + b);
}
show3(12, 5);

let arr1 = [1, 3, 5, 7, 9]
let arr2 = [2, 4, 6, 8, 10]
console.log(...arr1); //展开一个数组
let arr3 = [...arr1, ...arr2]//连接数组

//在函数中使用
function sum (...numbers)
{
    return numbers.reduce((preValue, currentValue) =>
    {
        return preValue + currentValue
    })
}
console.log(sum(1, 2, 3, 4));

//构造字面量对象时使用展开语法
let person = { name: 'tom', age: 18 }
let person2 = { ...person }
//console.log(...person); //报错,展开运算符不能展开对象
person.name = 'jerry'
console.log(person);  // { name: 'jerry', age: 18 }
console.log(person2);  // { name: 'tom', age: 18 }

//合并并更改
let person3 = { ...person, name: 'jack', address: "地球" }
console.log(person3);

// 删除并返回一个新变量
// 方式1:
let { name, ...newPerson } = person3
console.log(newPerson);
// 方式2:
let newPerson2 = (({ age, address }) => ({ age, address }))(person3)
console.log(newPerson2);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

臧小川

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值