SE6 不定参数和默认参数详解和使用细节

来源:互联网 发布:mac口红代购价格多少 编辑:程序博客网 时间:2024/05/28 05:15

在SE5以前我们通常通过arguments类数组对象来引用不定形参,SE6则使用了一种叫做不定参数的写法,比起隐式的arguments要直观的多。

不定参数使用...参数名来指定一个不定参数,参数名指向一个数组,传进来的参数除开指定的形参外,其他的都存在这个数组中。如果调用famlies("Jhon","sily","mery");则others=["sily","mery"]。

function families(father,...others){alert(father);for( let name of othres){alert(name);}}

不定参数只能是最后一个参数,函数调用时,前面的参数正常填充,剩余的参数填充到不定形参数组,如果没有多余的参数,则不定形参是一个空数组[],而永远不会是undefined。


不定参数不能有默认值


function familis(father,...others="mery"){}//SyntaxError: rest parameter may not have a default

标准说不定参数函数体中禁止arguments对象,但是我在最新版火狐上亲测,是没有问题的,现阶段不定参数还没有通用,保留了arguments对象,但为了和未来兼容,建议遵循标准。火狐亲测如下:

(function familis(father,...others){console.log(arguments[1]);})("Jon","jil");//jil

默认参数

SE5以前未传值的参数有undefined进行填充,SE6对此进行了优化,可以指定一个默认参数,如果传入参数则使用实参值,不然使用默认值。

function familis(father="Jhon",mother="mery"){console.log(father);console.log(mother);}

使用默认参数要注意几点:


1、参数表达式从左向右求值

(function familis(father="Jhon",mother=father=="Jhon"? "mery":"bord"){console.log(father);console.log(mother);})()//Jhon //mery

2、传递undefined值相当于不传值,还是会调用默认参数。

3、没有默认值的参数默认默认值为undefined。

4、默认参数表达式可以放在没有默认值的参数左边

(function familis(father="Jhon",mother){console.log(father);})()//Jhon

5、函数变量提升

(function familis(father="Jhon"){function father(){}return father;})()//function father()





0 0
原创粉丝点击