ES6函數總結

1  函數的默認值

function add(a = 100, b = 2
    return a + b           
}                          
console.log( add());       
console.log(add(1,4));     

300
5
unction Point(name = '張三' , age = 20) {                   
   this.name = name,                                      
   this.age = age                                         
                                                          
onst a = new Point()                                      
onsole.log(a)                                             
onst b = new Point("李四",60);                              
onsole.log(b)                                             

Point { name: '張三', age: 20 }
Point { name: '李四', age: 60 }

注意   1  變量在作爲默認參數時,不能在用let或者const再一次定義   

           2   默認參數中不能出現相同的變量名

           3  默認參數不是傳值的而是執行一次計算一次 

let number = 100;        
function add1( a = number
  return 100 + number    
}                        
const number1 = add1();  
console.log(number1);    
number = 1;              
const number2 = add1()   
console.log(number2)     

200
101

2   與解構賦值連用

function add({a,b = 200}) {                
  return a + b                             
}                                          
const a = add({a:10});                     
const b = add({});                         
const c = add({a:2,b:3}) ; 
const d = add()                
console.log(`${a} -------${b} ------${c}`);

TypeError: Cannot destructure property `a` of 'undefined' or 'null'.
210 -------NaN ------5

上述情況下d函數報錯在a參數沒有生成 故可以修改成以下形式,即沒有參數時賦值爲空對象

function add({a,b = 200} = {}) {        
  return a + b                          
}                                       

const d = add()
NaN

  區分兩種不同的情況

function see({a = 1,b = 1} = {}) {
     console.log(`${a} --------${b}`)
}
function see1({a,b} = {a:10,b:20}) {
      console.log(`${a} --------${b}`)
}

see()
see1()
see({})
see1({})
see({a:100})
see1({b:200})

1 --------1
10 --------20
1 --------1
undefined --------undefined
100 --------1
undefined --------200
see1()的不同之處在於雖然設置了值但是沒有設置默認的值,故當傳入參數爲空對象或者只有不全屬性的參數那麼缺失的屬性是找不到對應的值,所以是undefined
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章