1. 程式人生 > >ES6的常用語法

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()