函数可以给默认参数
function show(a = '默认', b = '系统'){ //不传参数时显示的值
console.log(a,b);
}
show('hello'); // hello 系统
函数参数默认已经定义了,不能再用let,const声明了
//以下程序报错
function demo(a = 18){//函数里的参数默认已经定义
let a = 10;//这里不能再重复定义
console.log(a);
}
demo()
扩展运算符(三个点)
可以展开数组
var arr = ['banana','apple','orange'];
console.log(arr);//Array(3) ["banana", "apple", "orange"]
console.log(...arr);//banana apple orange
运用于传参
function demo(...a){
console.log(a);//Array(5) [1, 2, 3, 4, 5]
}
demo(1,2,3,4,5);
将字符串转为数组
[...'hello']
// [ "h", "e", "l", "l", "o" ]
复制一个数组,新数组发生改变时不改变原数组的值
var arr = [1,3,2,7,5];
var arr2 = [...arr];
arr.pop();
arr2.push(10);
console.log(arr);//Array(4) [1, 3, 2, 7]
console.log(arr2);//Array(6) [1, 3, 2, 7, 5, 10]
直接引用时一个数组发生改变时,另一个数组也会发生改变
var arr = [1,3,2,7,5];
var arr2 = arr;
arr.pop();
arr2.push(10);
console.log(arr);//Array(4) [1, 3, 2, 7, 10]
console.log(arr2);//Array(6) [1, 3, 2, 7, 10]
箭头函数(=>)
格式
let 函数名 = () => {
函数体在这里插入代码片
}
注意点
1.this:箭头函数里,this指向定义函数时指向的对象,不再是运行时所在的对象
var id = 10;
let json = {
id : 1,
name : 'yang',
say : function(){
setTimeout(function(){//普通函数
alert(this.id);//10
},1000)
},
show : function(){
setTimeout(() => {//使用了箭头函数
alert(this.id);//1
}, 2000);
},
}
json.say();
json.show();
2.arguments:箭头函数里没有arguments,用‘…’。
let show=()=>{
console.log(arguments);//报错 ReferenceError: arguments is not defined
}
show(1,5,7,3)
let show=(...arguments)=>{
console.log(arguments);//Array(4) [1, 5, 7, 3]
}
show(1,5,7,3)
3.箭头函数不能当构造函数
let show=()=>{
this.name = 'yang'
}
let s = new show();
console.log(s.name);//报错 TypeError: show is not a constructor