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
发布了26 篇原创文章 · 获赞 79 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_25502269/article/details/105292451