es6定义变量
<script>
{
// es6如何定义变量,定义变量特点
// js定义:var a = 10
// es6写法定义变量,使用关键字 let
// let定义变量有作用范围
var a = 10
let b = 20
}
//在代码块外面输出
console.log(a)
console.log(b) //Uncaught ReferenceError: b is not defined
</script>
<script>
//var 可以声明多次
//let 只能声明一次
var a =1
var a =2
let m = 10
let m = 20
console.log(a)
console.log(m) //Uncaught SyntaxError: Identifier 'm' has already been declared
</script>
数组结构
<script>
//传统写法
let a =1,b=2,c=3
console.log(a,b,c) // 1 2 3
//es6写法
let [x,y,z] = [10,20,30] // 10 20 30
console.log(x,y,z)
</script>
对象结构
<script>
let user = {name:"helen",age:18}
//传统写法
let name1 = user.name
let age1 = user.age
console.log(name1,age1)
//es6写法
let {name,age} = user
console.log(name,age)
</script>
定义方法调用
<script>
//传统
const person1 = {
sayHi:function(){
console.log("Hi")
}
}
person1.sayHi()
//es6
const person2 = {
sayHi2(){
console.log("Hi2")
}
}
person2.sayHi2()
</script>
对象拓展运算符
<script>
//对象复制
let person1 = {"name":"lucy","age":20}
let person2 = {...person1}
console.log(person2)
//对象合并
let name = {name:'mary'}
let age = {age:40}
let p2 = {...name,...age}
console.log(p2)
</script>
箭头函数
<script>
//传统
var f1 = function(a){
return a
}
console.log(f1(1)) //1
//es6
var f2 = a => a
console.log(f2(2)) //2
//当箭头函数没有参数或者有多个参数,要用()括起来
//当箭头函数函数体有多行语句,用{}包裹起来,表示代码块
//当只有一行语句,并且需要返回结果时,可以省略{},结果会自动返回
//传统
var f3 = function(a,b){
return a+b
}
console.log(f3(1,2)) //3
//es6
var f4 = (a,b) => a+b
console.log(f4(3,2)) //5
</script>