es6是一套标准、规范
js很好的遵守了es6
<script>
//es6如何定义变量,定义变量特点
//js定义:var var a = 10;
//es6写法:let let a = 10; 有局部作用范围
{
var a = 10;
let b = 20;
}
//在代码块外调用 输出
console.log(a)
console.log(b) //Uncaught ReferenceError: b is not define at 01.html:11:17
</script>
//var 可以多次声明
//let只能一次声明
<script>
var a = 1
var a = 2
let m = 10
let m = 20 //Uncaught SyntaxError: Identifier 'm' has already been declared
console.log(a)
console.log(m)
</script>
<script>
//定义常量
const PI = "3.1415"
//常量值一旦定义 不能再改变
PI = 3 //Uncaught TypeError: Assignment to constant variable.
//定义常量必须初始化
//const AA
</script>
<script>
//1、数组解构
// 传统
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>
对象解构
<script>
//2、对象解构
let user = {name: 'Helen', age: 18}
// 传统
let name1 = user.name
let age1 = user.age
console.log(name1, age1)
// ES6
let { name, age } = user//注意:结构的变量必须是user中的属性
console.log(name, age)
</script>
<script>
//1 使用`可以实现换行
let str1 = `hello,
es6 demo up!`
console.log(str1)
</script>
<script>
//1 使用`可以实现换行
let str1 = `hello,
es6 demo up!`
console.log(str1)
// 2、字符串插入变量和表达式。变量名写在 ${} 中,${} 中可以放入 JavaScript 表达式。
let name = "Mike"
let age = 27
let info = `My Name is ${name},I am ${age+1} years old next year.`
console.log(info)
// My Name is Mike,I am 28 years old next year.
</script>
<script>
//1 使用`可以实现换行
let str1 = `hello,
es6 demo up!`
console.log(str1)
// 2、字符串插入变量和表达式。变量名写在 ${} 中,${} 中可以放入 JavaScript 表达式。
let name = "Mike"
let age = 27
let info = `My Name is ${name},I am ${age+1} years old next year.`
console.log(info)
// My Name is Mike,I am 28 years old next year.
// 3、字符串中调用函数
function f(){
return "have fun!"
}
let string2 = `Game start,${f()}`
console.log(string2); // Game start,have fun!
</script>
对象声明:
<script>
const age = 12
const name = "Amy"
// 传统
const person1 = {age: age, name: name}
console.log(person1)
// ES6
const person2 = {age, name}
console.log(person2) //{age: 12, name: "Amy"}
</script>
<script>
//传统方式
const person1 = {
sayHi:function(){
console.log("hi")
}
}
//调用:
person1.sayHi()
//es6:
const person2 = {
sayHi(){
console.log("hi")
}
}
</script>
对象扩展对象运算符
<script>
//1.对象复制
let person1 = {"name":"lucy","age":20}
let person2 = {...person1}
console.log(person2)
// 2、合并对象
let age = {age: 15}
let name = {name: "Amy"}
let person3 = {...age, ...name}
console.log(person2) //{age: 15, name: "Amy"}
</script>
<script>
//传统创建方法
var f1 = function(a){
return a+1
}
//ES6
var f2 = a => a+1
// 当箭头函数没有参数或者有多个参数,要用 () 括起来。
// 当箭头函数函数体有多行语句,用 {} 包裹起来,表示代码块,
// 当只有一行语句,并且需要返回结果时,可以省略 {} , 结果会自动返回。
var f3 = (a,b) => {
let result = a+b
return result
}
console.log(f3(6,2)) // 8
// 前面代码相当于:
var f4 = (a,b) => a+b
</script>