ECMAScript-扩展运算符与rest参数

it2025-04-02  11

文章目录

一、扩展运算符与rest参数...运用1. 扩展运算符:把数组或者类数组展开成用逗号隔开的值2. rest参数:把逗号隔开的值组合成一个数组

一、扩展运算符与rest参数
…运用
1. 扩展运算符:把数组或者类数组展开成用逗号隔开的值
// 扩展运算法 function foo(a, b, c){ console.log(a, b, c) // 1 2 3 } let arr = [1, 2, 3] foo(...arr) // 数组合并 let arr1 = [1, 2, 3] let arr2 = [4, 5, 6] // es5的做法 Array.prototype.push.apply(arr1, arr2) // es6的做法 arr1.push(...arr2) console.log(arr1) // [1, 2, 3, 4, 5, 6] // 字符串打散放入数组中 let str = 'zhangsan' let arr = [...str] console.log(arr) //["z", "h", "a", "n", "g", "s", "a", "n"]
2. rest参数:把逗号隔开的值组合成一个数组
// rest参数 // 求和,但是x,y,z 不定参 function foo(x, y, z) { let sum = 0 // es5的做法 // Array.prototype.forEach.call(arguments, function(item) { // sum += item // }) // es6的做法 Array.from(arguments).forEach(function(item){ sum += item }) return sum } console.log(foo(1, 2)) console.log(foo(1, 2, 3)) // rest做法 function foo(...args){ let sum = 0 args.forEach(function(item){ sum += item }) return sum } console.log(foo(1, 2)) console.log(foo(1, 2, 3)) // 剩余参数 function foo(x, ...args){ console.log(x) // 1 console.log(args) // [2, 3] } foo(1, 2, 3) // 与解构联合使用 let [x, ...y] = [1, 2, 3] console.log(x) // 1 console.log(y) // [2, 3]
最新回复(0)