ES6的函数rest参数使用小结
作者:厦门德仔
ES6的函数rest参数用法
es6中引入了rest参数,样式形如…xxx,用于获取函数的多余参数,这样就不需要使用arguments对象了。rest参数搭配的一个变量是一个数组,该变量将多余的参数放入数组中。例如:
function add(...value){
console.log(value);
let sum=0;
for(var val of value){
sum+=val
}
return sum
}
add(2,3,5);//10上面代码的add函数是一个求和函数,利用rest参数,可以向该函数传入任意数目的参数。
下面是一个rest参数代替arguments变量的例子:
function sortNumbers(){
return Array.prototype.slice.call(arguments).sort();
}
//rest写法
const sortNumbers=(...numbers)=>numbers.sort();上面两种写法rest参数的写法更加自然简洁。
arguments对象不是数组,只是一个类数组对象。为了使用数组的方法,得使用Array.prototype.slice.call先将其转为数组。rest参数就不存在这个问题,它就是一个真正的数组,数组的方法都可以使用。下面是一个利用rest参数改写数组的push方法。
function push(array,...items){
items.forEach(function(item){
array.push(item);
console.log(item);
})
}
var a=[];
push(a,1,2,3);还需要注意的是
rest参数之后不能有其他参数,否则会报错。
函数的length属性不包括rest参数。
(function(a) {}).length // 1
(function(...a) {}).length // 0
(function(a, ...b) {}).length // 1ES6-rest参数
rest参数
一.rest参数
- rest参数(形式为"…变量名"),用于获取函数的多余参数,这样就不需要使用arguments(参数)对象了.
- rest参数搭配的变量是一个数组,该变量将多余的参数放入数组中.
function add(...a){
let sum = 0;
for(var val of a){
sum += val;
}
return sum;
}
add(2,5,3);//10add函数是一个求和函数,利用rest参数,可以向该函数传入任意数目的参数.
3. rest参数代替arguments变量
// arguments变量的写法
function sortNumbers() {
return Array.prototype.slice.call(arguments).sort();
}
// rest参数的写法
const sortNumbers = (...numbers) => numbers.sort();4.res参数中的变量代表一个数组,所以数组特有的方方都可以用于这个变量.下面是一个利用rest参数改写数组push方法的例子
function push(array, ...items){
//forEach为每一个
items.forEach(function(item){
array.push(item);
console.log(item);
});
}
var a = [];
push(a, 1, 2, 3);5.rest参数之后不能再有其他参数(即只能是最后一个参数),否则会报错.
6.函数的length属性,不包括rest参数
(function(a){}).length //1
(function(...a){}).length //0
(function(a,...b){}).length //1二.扩展运算符
1.含义:
扩展运算符(spread)是三个点(…).它好比rest参数的逆运算,将一个数组转为用逗号分隔的参数序列.
console.log(...[1,2,3])
//1 2 3
console.log(1,...[2,3,4],5);
//1 2 3 4 5
[...document.querySelectorAll('div')]
//[<div>,<div>,<div>]2.该运算符主要用于函数调用
function add(x, y) {
return x + y;
}
var numbers = [4, 38];
add(...numbers) // 423.扩展运算符与正常的函数参数可以结合使用,非常灵活
function f(v, w, x, y, z) {
console.log(v); //-1
console.log(w); //0
console.log(x); //1
console.log(y); //2
console.log(z); //3
}
var args = [0, 1];
f(-1, ...args, 2, ...[3]);三.扩展运算符的应用
1.合并数组
//ES5 [1, 2].concat(more) //ES6 [1, 2, ...more] var arr1 = ['a','b']; var arr2 = ['c']; //ES5的合并数组 arr1.concat(arr1, arr2); //ES6的合并数组 [...arr1, ...arr2]
四.严格模式
1.从ES5开始,函数内部可以设定为严格模式
function doSomething(a,b){
'use strict'
//code
}2.ES6做了一点修改,规定只要函数参数使用了默认值、解构赋值、或者扩展运算符,那么函数内部就不能显式设置为严格模式,否则就会报错.
五.name属性
1.函数的name属性,返回该函数的函数名.
function foo(){}
foo.name //"foo"如果将一个匿名函数赋值给一个变量,ES5的name属性, 会返回空字符串,而ES6的name属性会返回实际的函数名.
2. function构造函数返回的函数实例,name属性的值为"anonymous".
function foo(){}
foo.name //"foo"3.bind返回的函数,name属性值会加上“bound ”前缀。
function foo() {};
foo.bind({}).name // "bound foo"
(function(){}).bind({}).name // "bound "参考文档
到此这篇关于ES6的函数rest参数用法的文章就介绍到这了,更多相关ES6 rest参数用法内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
