ES6中参数的默认值语法介绍
前言
在ES6如果函数参数没有值或未定义的,默认函数参数允许将初始值初始化为默认值。下面来看看详细的介绍吧。
语法
function[name]([param1[=defaultValue1][,...,paramN[=defaultValueN]]]) { statements }
描述
在JavaScript中,函数默认参数定义。然而,在某些情况下,设置不同的默认值可能是有用的。这是默认参数可以帮助的地方。
在过去,设置默认值的一般策略是在函数体中测试参数值,如果它们是未定义的就分配一个值。如果在下面的例子中,在调用过程中b没有提供值,它的值将是undefined当对a*b求值并且调用这个乘法的时候将返回NaN。
functionmultiply(a,b){ varb=(typeofb!=='undefined')?b:1; returna*b; } multiply(5);//5
在ES6中设置默认参数,对函数体的检查是不必须的了。现在,你可以简单的在函数头设置默认值:
functionmultiply(a,b=1){ returna*b; } multiply(5);//5
例子
通过未定义
在第二个函数调用中,即使第二个参数明确地被设置为undefined(虽然不是null),但是这个函数的颜色参数有一个默认值。
functionsetBackgroundColor(element,color='rosybrown'){ element.style.backgroundColor=color; } setBackgroundColor(someDiv);//colorsetto'rosybrown' setBackgroundColor(someDiv,undefined);//colorsetto'rosybrown'too setBackgroundColor(someDiv,'blue');//colorsetto'blue'
调用时求值
默认参数在调用时计算的,所以不像在Python中,一个新的对象是每次调用函数创建。
functionappend(value,array=[]){ array.push(value); returnarray; } append(1);//[1] append(2);//[2],not[1,2]
甚至适合于函数和变量
functioncallSomething(thing=something()){returnthing} functionsomething(){ return"sth"; } callSomething();//sth
默认参数可以提供给以后的默认参数
已经遇到的参数可以提供给以后的默认参数:
functionsingularAutoPlural(singular,plural=singular+"s", rallyingCry=plural+"ATTACK!!!"){ return[singular,plural,rallyingCry]; } //["Gecko","Geckos","GeckosATTACK!!!"] singularAutoPlural("Gecko"); //["Fox","Foxes","FoxesATTACK!!!"] singularAutoPlural("Fox","Foxes"); //["Deer","Deer","Deer...change."] singularAutoPlural("Deer","Deer","Deerpeaceablyandrespectfully petitionthegovernmentforpositivechange.")
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对毛票票的支持。