ES6语法

变量声明和赋值

声明变量

使用letconst声明变量,特点:

  1. letconst声明的变量没有预解析
  2. const定义的值是常量,不能修改

字符串模板

let name = "xiaom"
let age = 13

alert(`name is ${name},age is ${age}`) // name is xiaom,age is 13

解构赋值

数组的解构赋值

const add = [1,2,3]
let [a,b,c] = arr
console.log(a,b,c) // 1,2,3

对象的解构赋值

const obj = {name: "tom","address":"beijing","age":100}
let {name,age} = obj
console.log(name, age)

函数参数的解构赋值

const person = {name:"xiaom",age:11}
function printPerson({name,age}){
	console.log(`姓名:${name} 年龄:${age}`)
}

printPerson(person) // 姓名:xiaom 年龄: 11

扩展运算符

相当于将数组展开

<script>
    let arr = [1,2,3]
    let arr2 = [...arr,4]
    alert(arr2) // 1,2,3,4  

    function fnAdd(a,b,c) {
        alert(a+b+c)
    }
    fnAdd(...arr) // 6

    function fnAlert(...arr) {
        alert(arr[0])
        alert(arr[1])
    }
    fnAlert(1,2)    // 1, 2
</script>

函数

箭头函数

箭头函数可以理解匿名函数的第二种写法,箭头函数的作用可以在对象中绑定this

<script>
    // 通过匿名函数赋值来定义函数
    let fnNiming = function(a,b) {
        alert(a+b)
    }
    fnNiming(4,5) // 9

    // 通过箭头函数的写法
    let fnJiantou = (a,b)=> {
        alert(a+b)
    }
    fnJiantou(4,5) // 9

    // 一个参数可以省略小括号
    let fnJiantou2 = a=> {
        alert(a)
    }
    fnJiantou2("haha") // haha

    // 没有参数要写括号
    let fnJiantou3 = () => {
        alert(1)
    }
    fnJiantou3() // 1

    // 箭头函数可以绑定对象中的this
    let person = {
        name: "hau",
        age: 13,
        showName: function() {
            setTimeout(() => {
                alert(this.name)    // 如果是一般匿名函数,this指的是window对象
            },1000)
        }
    }
    person.showName() // hau
</script>
posted @ 2020-10-11 19:56  lovy11111  阅读(107)  评论(0)    收藏  举报