ES 6 函数参数

2018-04-03  本文已影响0人  c6e71129966d

参数默认值

在es6之前,定义函数的时候,是通过逻辑或者操作符来达到目的。

现在在定义函数的时候可以指定参数的默认值。

以前:

function say(name){

    var name = name || '小明';

    console.log(name);

}

es6:

function sayHello(name = 'hello'){

console.log(name);

}

调用函数及结果

say();              //输出:小明

say('小红 ');  //输出:小红

sayHello();    //输出:hello;

sayHello("你好");//输出:你好

函数的length属性

指定了默认值之后,函数的length属性,只返回没有指定默认值的参数的个数。

指定了默认值之后,length属性失真。

(function(a){}).length   // 1

(function(a = 5,b ){}).length  // 1

(function(a = 5){}).length    // 0

rest参数

...变量名

function add (...val){

let sum = 0;

for(var item of val){

sum += item;

}

return sum;

}

add(1,2,5);  //8

rest参数  是一个数组。

rest参数只能是最后一个参数,之后不能再有其他参数。

函数的length属性,不包括rest参数

(function(a,b,c = 4,...d){}).length   //2

上一篇 下一篇

猜你喜欢

热点阅读