ES6中參數(shù)的默認值語法介紹
前言
在ES6如果函數(shù)參數(shù)沒有值或未定義的,默認函數(shù)參數(shù)允許將初始值初始化為默認值。下面來看看詳細的介紹吧。
語法
function [name]([param1[ = defaultValue1 ][, ..., paramN[ = defaultValueN ]]])
{
statements
}
描述
在JavaScript中,函數(shù)默認參數(shù)定義。然而,在某些情況下,設置不同的默認值可能是有用的。這是默認參數(shù)可以幫助的地方。
在過去,設置默認值的一般策略是在函數(shù)體中測試參數(shù)值,如果它們是未定義的就分配一個值。如果在下面的例子中,在調(diào)用過程中b沒有提供值,它的值將是undefined 當對 a*b 求值并且調(diào)用這個乘法的時候?qū)⒎祷豊aN。
function multiply(a, b) {
var b = (typeof b !== 'undefined') ? b : 1;
return a*b;
}
multiply(5); // 5
在ES6中設置默認參數(shù),對函數(shù)體的檢查是不必須的了?,F(xiàn)在,你可以簡單的在函數(shù)頭設置默認值:
function multiply(a, b = 1) {
return a*b;
}
multiply(5); // 5
例子
通過未定義
在第二個函數(shù)調(diào)用中,即使第二個參數(shù)明確地被設置為undefined(雖然不是null),但是這個函數(shù)的顏色參數(shù)有一個默認值。
function setBackgroundColor(element, color = 'rosybrown') {
element.style.backgroundColor = color;
}
setBackgroundColor(someDiv); // color set to 'rosybrown'
setBackgroundColor(someDiv, undefined); // color set to 'rosybrown' too
setBackgroundColor(someDiv, 'blue'); // color set to 'blue'
調(diào)用時求值
默認參數(shù)在調(diào)用時計算的,所以不像在Python中,一個新的對象是每次調(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
默認參數(shù)可以提供給以后的默認參數(shù)
已經(jīng)遇到的參數(shù)可以提供給以后的默認參數(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é)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。
相關文章
JavaScript箭頭函數(shù)與普通函數(shù)的區(qū)別示例詳解
這篇文章主要為大家介紹了JavaScript箭頭函數(shù)與普通函數(shù)的區(qū)別示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-10-10

