es6是一种前端的标准
- es6 let变量
<script >
//es中定义一个变量,定义变量的特单
//js定义 var a = 1;
//es6写法定义变量,使用关键字let
{
//创建代码块,定义变量
var a = 10;
let b = 20;
}
//在代码块外面输出
console.log(a);
console.log(b);
</script>
输出结果
10
Uncaught ReferenceError: b is not defined
- es6 let变量的特点
<script >
let a=1
let a=2
var b=10
var b=20
//在代码块外面输出
console.log(a);
console.log(b);//Uncaught SyntaxError: Identifier 'a' has already been declared
</script>
输出结果
//Uncaught SyntaxError: Identifier ‘a’ has already been declared
- es6 const声明变量``
<script>
//定义变量
const PI="3.1415"
//常量值一旦定义,不能改变
PI= 3 // 输出结果 Uncaught TypeError: Assignment to constant variable.
//at 03-const声明变量.html:5
//定义定义常量必须有值
const s //输出结果:Uncaught SyntaxError: Missing initializer in const declaration
</script>
- es6 数组结构
<script>
//传统写法
let a=1,b=2,c=3
console.log(a,b,c)
//es6写法
let [x,y,z]=[1,2,3]
console.log(x,y,z)
</script>
输出结果:
1 2 3
1 2 3
- es6 模板字符串
<script>
//定义对象
let user = {"name":"lucky","age":20}
//传统从对象里面获取值
let name1=user.name
let age1=user.age
console.log(name1+","+age1)
//es6获取对象值
let{name,age}=user
console.log(name+","+age)
</script>
输出结果
lucky,20
lucky,20
- es6 声明对象
<script>
const age = 12
const name = "luky"
//传统方式定义对象
const p1={name:name,age:age}
console.log(p1)
//es6定义变量
const p2={name,age}
console.log(p2)
</script>
输出结果
age: 12
name: “luky”;
age: 12
name: “luky”
- es6 定义方法简写
<script>
//传统方式定义的方法
const person1 = {
sayHi:function(){
console.log("Hi")
}
}
//调用
person1.sayHi()
//es6方法定义的方法
const person2 ={
sayHi(){
console.log("hi")
}
}
console.log(person2)
</script>
输出结果
Hi
ObjectsayHi: ƒ sayHi()
- es6 对象拓展运算符
<script>
// 1 对象赋值
let person = {"name":"lucky","age":20}
let someone= {...person}
console.log(someone)
//2合并对象
let name={name:"mary"}
let age={age:20}
let p2={...name,...age}
console.log(p2)
</script>
输出结果
age: 20
name: “lucky”
age: 20
name: “mary”
- es6 箭头函数
<script>
//传统
var f1=function(a){
return a+1;
}
console.log(f1(2))
//使用箭头函数改造
var f2 = m => m+1
console.log(f2(2))
//双参数
var f3 = function(a,b){
return a+b
}
console.log(1,2)
//箭头函数简化
var f4 = (a,b) =>a+b
console.log(f4(1,2))
</script>
输出结果
3
3
1 2
3