ES6学习笔记(函数扩展)
1.默认参数
function people({name,age = 30}={}) {
console.log(name,age);
};
people({name:3}); //输出 3 30
people(); //输出 undefined 30
2.扩展运算符(剩余参数)
在ES6之前,如果要在方法内将多字符整合为一个数组,一般会使用以下写法
function sum() {
let args = Array.prototype.slice.call(arguments);
console.log(args);
}
sum(1,2,123,'qwer');
ES6之后,使用运算符可以简化成这样
function sum() {
let args = [...arguments];
console.log(args);
}
sum(1,2,123,'qwer');
或者这样
function sum() {
let [...args] = arguments;
console.log(args);
}
sum(1,2,123,'qwer');
或者使用“剩余参数”的概念,可以简化成这样
function sum(...args) {
console.log(args);
}
sum(1,2,123,'qwer');
3.箭头函数
调用一个方法再进行赋值时,一般会写成这样
const add = function (a,b) {
return a+b;
}
如果使用箭头函数,可以简化成这样
const add = (a,b) => a+b;
如果函数内有多行代码,可以写成这样
const add = (a,b) =>{
a += 1;
return a+b;
}
还没有评论,来说两句吧...