常见网站类型,爱链接外链购买,自己怎么建设网站,深圳做网站比较好文章目录 前端知识点---rest(javascript)rest的用法基本语法特点使用场景与扩展运算符#xff08;spread#xff09;区别小练习 前端知识点—rest(javascript)
rest出现于ES2015
function doSum(a,b, ...args)
//示例中的args就是一个rest参数
//它会将后续的所有参数存储… 文章目录 前端知识点---rest(javascript)rest的用法基本语法特点使用场景与扩展运算符spread区别小练习 前端知识点—rest(javascript)
rest出现于ES2015
function doSum(a,b, ...args)
//示例中的args就是一个rest参数
//它会将后续的所有参数存储在名为args的数组中 在rest出现之前 还有一个东西叫arguments
但是arguments存在一些问题
松散模式下的性能问题 arguments和实参是双向绑定的 ,就是说 , 修改实参argument会发生变化 , 修改arguments 实参也会发生变化 ,arguments和实参的同步就带来了性能问题 ,严格模式下arguments和实参没有双向绑定就没有性能问题 arguments包含了所有的参数 , 这意味着要为所有的参数计算索引 , 才能获取参数没名字 必须是arguments加索引的方式访问所有参数箭头函数不能用不是数组
rest的用法
rest 参数用于将不定数量的参数组合成一个数组。它在函数定义中使用方便处理函数接收的多个参数尤其是当参数数量不确定时。
基本语法
使用三个点…表示 rest 参数语法如下
function myFunction(...args) {console.log(args); // args 是一个数组
}myFunction(1, 2, 3, 4, 5); // 输出[1, 2, 3, 4, 5]特点 收集剩余参数 rest 参数将从指定位置开始的所有剩余参数收集到一个数组中。 只能是最后一个参数 rest 参数必须是函数的最后一个参数。
function example(a, b, ...rest) {console.log(a); // 第一个参数console.log(b); // 第二个参数console.log(rest); // 剩余参数作为数组
}
example(1, 2, 3, 4, 5);
// 输出
// 1
// 2
// [3, 4, 5]
不能混用多个 rest 参数
一个函数中最多只能有一个 rest 参数并且它必须在最后。使用场景
替代 arguments 对象 传统上可以通过 arguments 对象访问函数中的所有参数但它不是一个真正的数组使用起来不如 rest 参数方便。
function oldWay() {console.log(arguments); // arguments 是类数组对象
}function newWay(...args) {console.log(args); // args 是真正的数组
}oldWay(1, 2, 3); // 输出{ 0: 1, 1: 2, 2: 3 }
newWay(1, 2, 3); // 输出[1, 2, 3]简化不定参数函数 比如计算任意数量数字的总和
function sum(...numbers) {return numbers.reduce((total, num) total num, 0);
}console.log(sum(1, 2, 3, 4)); // 输出10配合解构赋值 在对象或数组解构时rest 参数也非常有用
// 数组解构
const [first, second, ...rest] [1, 2, 3, 4, 5];
console.log(first); // 输出1
console.log(second); // 输出2
console.log(rest); // 输出[3, 4, 5]// 对象解构
const { a, b, ...others } { a: 1, b: 2, c: 3, d: 4 };
console.log(a); // 输出1
console.log(b); // 输出2
console.log(others); // 输出{ c: 3, d: 4 }与扩展运算符spread区别
Rest 参数rest用于“收集”不定数量的参数或元素形成一个数组。 扩展运算符spread用于“展开”数组或对象将其元素作为独立值。
function display(...args) {console.log(args); // 收集参数为数组
}const nums [1, 2, 3];
display(...nums); // 展开数组元素传入
// 输出[1, 2, 3]小练习
以下代码输出什么
function display(a, b, ...rest) {console.log(a);console.log(b);console.log(rest);
}display(10, 20, 30, 40, 50);答案 10 20 [30, 40, 50]