ES6的常用语法

1、块级作用域let 

{let name = 'let';console.log(name, '内')};console.log(name, '外')

里面的可以打印,外面的报错undefined

2、常量const

let name = 'let'; name = 'leon' 正常

const age = 18; age = 28 报错 不能再次赋值

3、字符串拼接(用反引号)

let name = 'leon'

let career = ‘前端’

原:console.log(‘我是’ + name + ',职业是' + career)

es6: console.log(`我是${name},职业是${career}`)

4、箭头函数 =>

()=> {do ..someing..} 

用途简化普通情况下的函数编写

原 const hello = function(name) {console.log(`hello!$(name)`)}

es6 const hello = (name) => {console.log(`hello!$(name)`)}

只有一条return语句是类似于kotlin和python中的lambda表达式

const sum = x => x + 2

console.log(sum(2)) --- 4

函数默认值

const hello = (name = 'word') => {console.log(`hello${name}`)}

不传值 hello() 默认输出 hello word

传值hello('leon') 输出 hello leon

this的作用域

5、展开符 ...

let arr = ['leon', 'tony']

function hello (name1, name2) {console.log(name1, name2)}

原 hello.apply(null, arr)或hell(arr[0], arr[1])

es6 hello(...arr)

6、object

let obj = {name: 'leon', age: '18'}

获取对象的所有key以数组展示:  Object.keys(obj) --- [‘name’, 'age']

获取对象的所有value以数组展示:Object.values(obj) --- [‘leon’, '18']

object的key和vlaue转成数组:Object.entries(obj) --- [['name', 'leon'],['age','18']]

let obj = {name: 'leon', age: '18'}

let obj2 = {phone: '221683', work: '前端'}

let obj3 = {...obj, ...obj2, day: '2017'}

7、数组与obj的赋值

原 let arr = ['leon', '18'];

let arr1 = arr[0]

let arr2 = arr[1]

es6 let [arr1, arr2] = arr --- leon 18

let obj = {name: 'leon', age: '18'}

let [obj1, obj2] = obj --- leon 18取得是value

类 class

class MyName {

    constructor() {this.name = 'leon'}

    sayHello(){console.log(`hello${this.name}`)}

}

my = new MyName

app.sayHello()

猜你喜欢

转载自blog.csdn.net/qq_37018847/article/details/85369608