参数变化
- 1.函数默认参数
function show(a='456',b='123'){
console.log(a,b);
}
show();
//不传参数则打印默认值,如果默认值也没有则是undefined undefined
//也可以穿的是一个对象
function show({x=0,y=0}={}){
console.log(x,y);
}
show();
- 2.函数参数默认已经定义了,不能再使用let,const再定义
function show(a=18){
let a = 101; //错误
console.log(a);
}
show();
扩展运算符、Rest运算符(…)
-
用法简介:
[1,2,3,4] -> … [1,2,3,4] -> 1 2 3 4,5
1 2 3 4 5 -> …1 2 3 4 5 -> [1,2,3,4,5] -
用法示例
let arr = ['apple','banana','orange'];
console.log(arr);
console.log(...arr);//apple banana orange
- 在参数上的用法
function show(...a){
console.log(a);
}
show(1,2,3,4,5);//[1,2,3,4,5]
//也可以反过来使用
function show(a,b,c){
console.log(a,b,c);
}
show(...[1,9,8]);
箭头函数
//写法
() =>{
//语句
//return
}
- 示例:
//示例1
// function show(){
// return 1;
// }
// console.log(show());
let show = ()=>1;
console.log(show());
//示例2
/* function show(a,b){
return a+b;
}
console.log(show(12,5)); */
let show = (a,b)=>a+b;
console.log(show(12,5));
//示例3
let show=(a=12,b=5)=>{
console.log(a,b);
return a+b;
};
show();
- 箭头函数this的指向
var id = 10; //用var定义一个全局变量,属于window, let,const不同
let json={
show:function(){
setTimeout(()=>{
alert(this.id);
},2000);
}
};
json.show();//结果为undefined
箭头函数中的this指向的是定义函数(show)所在的对象(json中),json中没有id所以为undefined
- 注意事项
1.箭头函数里面没有arguments, 用 ‘…’
2.箭头函数不能当构造函数
/* function show(){
this.name='abc';
} */
let show = ()=>{
this.name='abc';
}
let s=new show();
alert(s.name);
//Uncaught TypeError: show is not a constructor