ES6之函數的擴展

基本用法

function log(x,y = 'World') {
   console.log(x,y);
}
log('hello');   //hello World
log('hello', 'china');//hello china
log('hello',''); //hello 

與解構賦值默認值結合使用

# demo1
function foo({x, y = 5}) {
    console.log(x, y);
}

foo({});    //undefined, 5
foo({x:1}); //1,5
foo({x:1,y:2});//1,2
foo();  //x of undefined

ps:foo()參數爲對象,變量x和y纔會通過解構賦值而產生
   foo()參數不是對象,變量x和y就不會產生,從而報錯


# demo2
function foo({x = 0, y = 0} = {}) {
 return [x, y];
}

function foo1({x, y} = {x: 0, y: 0}) {
 return [x, y];
}

foo()           //[0,0];
foo1()          //[0,0]

foo({x:3,y:8})  //[3,8]
foo1({x:3,y:8}) //[3,8]

foo({x:3})      //[3,0]
foo1({x:3})     //[3,undefined]

foo({})         //[0,0]
foo1({})        //[undefined,undefined]

foo({z:3})      //[0,0]
foo1({z:3})     //[undefined,undefined]


ps: foo()參數默認值是空對象,但是設置了對向解構賦值的默認值;
    foo1()參數默認值是一個有具體屬性的函數,但是沒有設置對象解構賦值的默認值  

參數默認值的位置

function foo(x = 1, y) {
    return [x, y];
}

foo();  //[1,undefined]
foo(2); //[2,undefined]
foo(,1);//error
foo(undefined,1);//[1,1]
ps:有默認值的參數都不是尾參數,無法只省略該參數而不省略其後的參數,除非顯示輸入undefined

function foo(x=5,y=6) {
    return [x,y];
}
foo(undefined,null);//[5,null]

ps:上面代碼中,x==>undefined,處罰默認值,y==>null,並不觸發默認值

函數的length屬性

(function(a) {}).length;        //1
(function(a=5) {}).length;      //0
(function(a,b=5) {}).length;    //1
(function(...rest) {}).length;    //0   

ps:指定默認值後,函數的length屬性將返回沒有設置默認值得參數的個數,也就是參數設置默認值後,length的屬性失效,rest參數也不計入length屬性

rest參數


# 用於獲取函數的多餘參數
function add(...value) {
    let sum = 0;
    for (var val of value){
        sum += val;
    }
    return sum;
}

console.log(add(2, 5, 3));          //10

# 用rest參數代替arguments變量
const sortNumber = () => Array.prototype.slice.call(arguments).sort();  //arguments寫法

const sortNumbers = (...numbers) => numbers.sort();                     //rest寫法


# rest參數寫成數組push方法
function push(arr, ...values) {
    values.forEach(function (item) {
        arr.push(item);
        console.log(item);          
    });
}

var a = [];
push(a, 1, 2, 2, 3, 4, 5);

# rest參數之後不能再有其他參數(即他只能是最後一個參數),否則會報錯
//報錯
function fn(a,...items, c) {
    // ... code
}

# 函數的length屬性不包括rest參數
(function (a) {}).length;       // 1
(function (...a) {}).length;    // 0
(function (a,...b) {}).length;  // 1
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章