ES6中參數的預設值文法介紹,es6參數預設值文法

來源:互聯網
上載者:User

ES6中參數的預設值文法介紹,es6參數預設值文法

前言

在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.")

總結

以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的協助,如果有疑問大家可以留言交流,謝謝大家對幫客之家的支援。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.