前言
在ES6如果函數參數沒有值或未定義的,默認函數參數允許將初始值初始化為默認值。下面來看看詳細的介紹吧。
語法
function [name]([param1[ = defaultValue1 ][, ..., paramN[ = defaultValueN ]]]) { statements}
描述
在JavaScript中,函數默認參數定義。然而,在某些情況下,設置不同的默認值可能是有用的。這是默認參數可以幫助的地方。
在過去,設置默認值的一般策略是在函數體中測試參數值,如果它們是未定義的就分配一個值。如果在下面的例子中,在調用過程中b沒有提供值,它的值將是undefined 當對 a*b 求值并且調用這個乘法的時候將返回NaN。
function multiply(a, b) {var b = (typeof b !== 'undefined') ? b : 1;return a*b;}multiply(5); // 5
在ES6中設置默認參數,對函數體的檢查是不必須的了。現在,你可以簡單的在函數頭設置默認值:
function multiply(a, b = 1) { return a*b;}multiply(5); // 5
例子
通過未定義
在第二個函數調用中,即使第二個參數明確地被設置為undefined(雖然不是null),但是這個函數的顏色參數有一個默認值。
function setBackgroundColor(element, color = 'rosybrown') { element.style.backgroundColor = color;}setBackgroundColor(someDiv); // color set to 'rosybrown'setBackgroundColor(someDiv, undefined); // color set to 'rosybrown' toosetBackgroundColor(someDiv, 'blue'); // color set to 'blue'
調用時求值
默認參數在調用時計算的,所以不像在Python中,一個新的對象是每次調用函數創建。
function append(value, array = []) {array.push(value);return array;}append(1); //[1]append(2); //[2], not [1, 2]
甚至適合于函數和變量
function callSomething(thing = something()) { return thing }function something(){ return "sth";}callSomething(); //sth
默認參數可以提供給以后的默認參數
已經遇到的參數可以提供給以后的默認參數:
function singularAutoPlural(singular, plural = singular+"s", rallyingCry = plural + " ATTACK!!!") { return [singular, plural, rallyingCry ];}//["Gecko","Geckos", "Geckos ATTACK!!!"]singularAutoPlural("Gecko");//["Fox","Foxes", "Foxes ATTACK!!!"]singularAutoPlural("Fox","Foxes");//["Deer", "Deer", "Deer ... change."]singularAutoPlural("Deer", "Deer", "Deer peaceably and respectfully petition the government for positive change.")
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對武林網的支持。
新聞熱點
疑難解答