前言
在ES6如果函數(shù)參數(shù)沒(méi)有值或未定義的,默認(rèn)函數(shù)參數(shù)允許將初始值初始化為默認(rèn)值。下面來(lái)看看詳細(xì)的介紹吧。
語(yǔ)法
function [name]([param1[ = defaultValue1 ][, ..., paramN[ = defaultValueN ]]]) { statements}描述
在JavaScript中,函數(shù)默認(rèn)參數(shù)定義。然而,在某些情況下,設(shè)置不同的默認(rèn)值可能是有用的。這是默認(rèn)參數(shù)可以幫助的地方。
在過(guò)去,設(shè)置默認(rèn)值的一般策略是在函數(shù)體中測(cè)試參數(shù)值,如果它們是未定義的就分配一個(gè)值。如果在下面的例子中,在調(diào)用過(guò)程中b沒(méi)有提供值,它的值將是undefined 當(dāng)對(duì) a*b 求值并且調(diào)用這個(gè)乘法的時(shí)候?qū)⒎祷豊aN。
function multiply(a, b) {var b = (typeof b !== 'undefined') ? b : 1;return a*b;}multiply(5); // 5在ES6中設(shè)置默認(rèn)參數(shù),對(duì)函數(shù)體的檢查是不必須的了。現(xiàn)在,你可以簡(jiǎn)單的在函數(shù)頭設(shè)置默認(rèn)值:
function multiply(a, b = 1) { return a*b;}multiply(5); // 5例子
通過(guò)未定義
在第二個(gè)函數(shù)調(diào)用中,即使第二個(gè)參數(shù)明確地被設(shè)置為undefined(雖然不是null),但是這個(gè)函數(shù)的顏色參數(shù)有一個(gè)默認(rèn)值。
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'調(diào)用時(shí)求值
默認(rèn)參數(shù)在調(diào)用時(shí)計(jì)算的,所以不像在Python中,一個(gè)新的對(duì)象是每次調(diào)用函數(shù)創(chuàng)建。
function append(value, array = []) {array.push(value);return array;}append(1); //[1]append(2); //[2], not [1, 2]甚至適合于函數(shù)和變量
function callSomething(thing = something()) { return thing }function something(){ return "sth";}callSomething(); //sth默認(rèn)參數(shù)可以提供給以后的默認(rèn)參數(shù)
已經(jīng)遇到的參數(shù)可以提供給以后的默認(rèn)參數(shù):
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.")總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作能帶來(lái)一定的幫助,如果有疑問(wèn)大家可以留言交流,謝謝大家對(duì)VeVb武林網(wǎng)的支持。
新聞熱點(diǎn)
疑難解答