rest参数
一.rest参数
- rest参数(形式为"…变量名"),用于获取函数的多余参数,这样就不需要使用arguments(参数)对象了.
- rest参数搭配的变量是一个数组,该变量将多余的参数放入数组中.
function add(...a){
let sum = 0;
for(var val of a){
sum += val;
}
return sum;
}
add(2,5,3);//10
a函数是一个求和函数,利用rest参数,可以向该函数传入任意数目的参数.
- res参数代替arguments变量
// arguments变量的写法
function sortNumbers() {
return Array.prototype.slice.call(arguments).sort();
}
// rest参数的写法
const sortNumbers = (...numbers) => numbers.sort();
- 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);
- rest参数之后不能再有其他参数(即只能是最后一个参数),否则会报错.
- 函数的length属性,不包括rest参数
(function(a){}).length //1
(function(...a){}).length //0
(function(a,...b){}).length //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>]
- 该运算符主要用于函数调用
function add(x, y) {
return x + y;
}
var numbers = [4, 38];
add(...numbers) // 42
- 扩展运算符与正常的函数参数可以结合使用,非常灵活
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]);
三.扩展运算符的应用
-
合并数组
//ES5 [1, 2].concat(more) //ES6 [1, 2, ...more] var arr1 = ['a','b']; var arr2 = ['c']; //ES5的合并数组 arr1.concat(arr1, arr2); //ES6的合并数组 [...arr1, ...arr2]
四.严格模式
-
从ES5开始,函数内部可以设定为严格模式
function doSomething(a,b){ 'use strict' //code }
-
ES6做了一点修改,规定只要函数参数使用了默认值、解构赋值、或者扩展运算符,那么函数内部就不能显式设置为严格模式,否则就会报错.
五.name属性
-
函数的name属性,返回该函数的函数名.
function foo(){} foo.name //"foo"
如果将一个匿名函数赋值给一个变量,ES5的name属性, 会返回空字符串,而ES6的name属性会返回实际的函数名.
-
function构造函数返回的函数实例,name属性的值为"anonymous".
(new Function).name // "anonymous"
bind
返回的函数,name
属性值会加上“bound ”前缀。
function foo() {};
foo.bind({}).name // "bound foo"
(function(){}).bind({}).name // "bound "