1.Default Parameters (函数默认参数)
如:定义一个函数,x,y可选,z必传。
ES6语法:
function calc(x=1, y=1,z) {
console.log(x,y,z)
}
calc(undefined,undefined,3); // 1 1 3
传统写法:
function calc(x, y,z) {
x=x||1;
y=y||1;
console.log(x,y,z)
}
calc(undefined,undefined,3); // 1 1 3
需要注意的是:
- 1.定义了默认参数后,函数的length属性会减少:
function calc(x=1, y=1, z) {...}
console.log(calc.length) //0
function calc(z, x=1, y=1) {...}
console.log(calc.length) //1
function calc(m, n ,x=1, y=1, z) {...}
console.log(calc.length) //2
- 2.不能用
let
和const
再次声明默认值,var
可以
function calc(x=1, y=1,z) {
var x=5 //可以
let x=5 //报错
const x=5 //报错
console.log(x,y,z)
}
另外比较有趣的是:默认参数还可以是一个函数调用。
利用这个特性可以强制指定某参数必须传,不传就报错
function throwIf() {
console.log('error:url必传');
}
function ajax( url=throwIf(), async=true, success) {
return url;
}
ajax(); // 'error:url必传'
ajax("www.baodu.com") //"www.baodu.com"
2.模板字符串
在反引号包裹的字符串中,使用${NAME}
(模板占位符)语法来表示模板字符
var name="candy";
var age=20;
var str=name + ' is ' + age + ' years old.' //传统写法
var str=`${name} is ${age} years old.` //es6写法
如果你想在模板字符串中使用反引号或 ${
,你需要使用反斜杠 \ 将其转义
var str=`\${\`
console.log(str) // ${`
3.多行字符串
传统写法:
var roadPoem = 'Then took the other, as just as fair,nt'
+ 'And having perhaps the better claimnt'
+ 'Because it was grassy and wanted wear'
+ 'Though as for that the passing therent'
es6语法:
var roadPoem = `Then took the other, as just as fair,
And having perhaps the better claimnt
Because it was grassy and wanted wear,
Though as for that the passing therent`
4.解构赋值
(1) 解构赋值-数组
- 交换两个变量的值。如若已知
a=1
,b=2
,现在要交换两个变量的值:
传统写法:
var c; //需借助中间变量c
c=a;
a=b;
b=c;
es6写法:
[b,a]=[a,b]
- 可嵌套
[p1, [p2,p3], p4]=[1, [2,3], 4] //p1,p2,p3,p4 的值分别为1,2,3,4
[p1, arr, p4]=[1, [2,3], 4]
console.log(arr) //[2,3]
- 函数返回
function foo(){return [1,2]}
var [a,b]=foo();
console.log(a,b) //1, 2
- 忽略某个元素
[p1, , p3, , p5]=[1,2,3,4,5]
- 指定默认值
var [a=1,b=2,c=3]=[100,50]
console.log(a,b,c) //100,50,3
- rest 参数,接收剩余参数
var [p1,p2,p3,...tail]=[1,2,3,4,5,6]
console.log(tail) //[4,5,6]
(2) 解构赋值-对象
var obj={name,age}={name:"candy",age:20}
console.log(name, age) //candy, 20
console.log(obj.name, obj.age) //candy, 20
- 可嵌套
var obj={name:{firstName, lastName}}={name:{firstName:"candy",lastName:"chen"}}
console.log(firstName) //candy
console.log(obj.name) //{firstName: "candy", lastName: "chen"}
console.log(obj.name.firstName) //"candy"
- 使用默认值
var obj={first="candy",last="chen"}={}
console.log(first,last) //candy,chen
cosole.log(obj.first, obj.last) //undefined,undefined
5.箭头函数
- 无参数,必须有圆括号
()=>{statements}
//等价于以下传统写法:
function (){statements}
- 多个参数
(p1,p2,p3)=>{statements}
//等价于以下传统写法:
function (p1,p2,p3){statements}
- 只有一个参数,圆括号可选
p1=>{statements}
(p1)=>{statements}
- 有返回值,花括号可选
(p1,p2)=>express
(p1,p2)=>{return express}
(p1,p2)=>(express)
//等价于以下传统写法:
function foo(p1,p2){return express}
举个例子:
var foo=(p1,p2)=>p1-p2
foo(10,15) //-5
- 返回一个对象时,函数体外必须加圆括号
p1=>({foo:bar})
- 箭头函数内返回箭头函数
let foo=(a,b)=>c=>a+b+c
foo(1,2,3) //6
//等价于以下传统写法:
function foo(a,b){
return function(c){
return a+b+c
}
}