參數默認值數組
未提供參數,或將參數值指定爲undefined時,默認值會被使用。app
function add(a, b = 2, c = 3){ let result = a + b + c; console.log(result); } add(1); //6add(1,2); //6add(1,undefined,4); //7add(1,null,4);
參數默認值表達式ide
參數默認值除了是基本類型的值,也能夠執行一個函數來產生默認值。函數
function getValue(){return 5; }//未提供第二個參數時,getValue()纔會被調用 function add(a, b = getValue()){return a + b ; } console.log(add(1,1)); //2console.log(add(1)); //6
getValue()函數也能夠返回可變的值。get
let value = 5;function getValue(){return value++; } function add(a, b = getValue()){return a + b ; } console.log(add(1,1)); //2console.log(add(1)); //6console.log(add(1)); //7
能夠將前面的參數做爲後面參數的默認值(反之,後面參數做爲前面參數的默認值不行)it
function add(a, b = a){return a + b ; } console.log(add(1,1)); //2console.log(add(1)); //2
也能夠將前面的參數a做爲參數傳遞給一個函數來產生參數b的值。io
function getValue(value){return value + 5; }function add(a, b = getValue(a)){return a + b ; } console.log(add(1,1)); //2console.log(add(1)); //7
剩餘參數console
剩餘參數由三個點(...)與一個緊跟着的具名參數指定,它會是包含傳遞給函數的其他參數的一個數組。
函數只能有一個剩餘參數,而且它必須放在最後。ast
function add(a, ...last){ let b = 0;for(let i=0;i<last.length;i++){ b += last[i]; }return a + b ; } console.log(add(1)); //1console.log(add(1,2)); //3console.log(add(1,2,3)); //6
擴展運算符function
剩餘參數把多個獨立的參數合併到一個數組中;擴展運算符則容許將一個數組分割,並將各個項做爲分離的參數傳給函數。
//Math.max()方法接受任意數量的參數let a = 25, b = 50; console.log(Math.max(a,b)); //50//ES5或更早版本let values = [25,50,75,100]; console.log(Math.max.apply(Math, values)); //100//擴展運算符console.log(Math.max(...values));//100
箭頭函數
沒有參數
var f = () => 'Hello'; console.log(f()); //Hello
一個參數
var f = a => a * a; console.log(f(2)); //4
多個參數
var f = (a,b) => a + b; console.log(f(2,3)); //5
建立當即調用函數表達式
//傳統函數let f1 = function(name){return { getName: function(){return name; } } }("f1"); console.log(f1.getName()); //f1//箭頭函數let f2 = ((name) => {return { getName: function(){return name; } } })("f2"); console.log(f2.getName()); //f2