函数参数
-
所谓类数组对象,就是指可以通过索引属性访问元素并且拥有 length 属性的对象;
var arrLike = { 0: 'name', 1: 'age', 2: 'job', length: 3 }
-
在 ES5 中,函数经常会传入不定参数,在传入不定参数时,ES5 的给出的解决方案是通过 arguments 对象来获取函数调用时传递的参数。 arguments 对象不是一个数组,它是一个类数组对象;尽管 arguments 是一个类数组且可遍历的变量,但它终究不是数组,它不支持数组方法,因此不能调用 arguments.forEeach (…) 等数组的方法
function fn() { console.log(arguments); } fn('hello', 7, 'ES6')
-
ES6 给出了完美解决方案 —— 剩余参数
function fn(name, ...args) { console.log(name); // 基础参数 console.log(args); // 剩下的参数组成的数组 } fn('ES6'); // 'ES6' // [] fn('hello', 7, 'ES6'); // "hello" // [7, "ES6"]
解构剩余参数
-
数组的解构赋值
let array = [1, 2, 3, 4, 5]; let [a, b, ...others] = array; console.log(a); // 1 console.log(b); // 2 console.log(others); // [3, 4, 5]
-
对象的解构赋值
let {a, b, ...others } = {a: 1, b: 2, c: 3, d: 4, e: 5} console.log(a); // 1 console.log(b); // 2 console.log(others); // {c: 3, d: 4, e: 5}
小结
-
剩余参数是为了能替代函数内部的 arguments 而引入的;
-
和展开语法相反,剩余参数是将多个单个元素聚集起来形成一个单独的个体的过程;
ES6+ 展开语法
上一篇