剩余参数 和 spread参数


三点区分:

剩余参数 rest(用于获取函数的多余参数) 和 spread参数(扩展运算符, 好比rest的逆运算):

形式都是三点加变量  ...val

有时候很迷惑 如何区分:

rest:  用于获取函数的多余参数 如果是用在函数形参中 , 获取的到的是一个数组的集合形式, 无论传多少参数 ,接收的是除了它前面形参的其他参数的集合, 只能放到最后(不然会报错) :这个时候 是剩余参数; 箭头函数可以用这个来代替普通函数中的 arguments

function fn(param1,...rest) {
console.log('param1====', param1)
 console.log('rest====', rest)
}
fn(1, 2, 3, 4, 5, 6)
vconsole.min.js?65ce:10 param1==== 1
vconsole.min.js?65ce:10 rest==== (5) [2, 3, 4, 5, 6]


let list = [1, 2,3 ,4 ,5]
[a, ...rest] = list
(5) [1, 2, 3, 4, 5]
rest
(4) [2, 3, 4, 5]

用在函数的实参里面,这个时候 是展开 spread 参数

用来传递多个参数

function fn1(a, b , c, d, e ) {
console.log('a====', a) 
console.log('b====', b) 
console.log('c====', c) 
console.log('d====', d)
 console.log('e====', e)
} 
let arr = [1, 2,3 ,4 ,5 ,6]
fn1(...arr)
vconsole.min.js?65ce:10 a==== 1
vconsole.min.js?65ce:10 b==== 2
vconsole.min.js?65ce:10 c==== 3
vconsole.min.js?65ce:10 d==== 4
vconsole.min.js?65ce:10 e==== 5

获取一个数组元素的最大值
let arr = [1,4 ,7 , 5]

Math.max(...arr)  // 传递实参

7

俩个数组拼接
let arr1 = [6,7,9]

arr1.push(...arr)

arr1

(7) [6, 7, 9, 1, 4, 7, 5]

可以用来连接对象或者数组, 这个时候 是展开 spread 参数

let obj1 = {a:'aaaa', b:'bbbb'}
let obj2 = {...obj1, c:'cccc'}
console.log('obj2====', obj2)
obj2==== {a: 'aaaa', b: 'bbbb', c: 'cccc'}


let arr1 = [a, b]
let arr2 = [...arr1, c, d]
console.log('arr2====', arr1)

let arr1 = ['a', 'b']
let arr2 = [...arr1, 'c', 'd']
console.log('arr2====', arr2)
vconsole.min.js?65ce:10 arr2==== (4) ['a', 'b', 'c', 'd']

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值