ES2015的目標(biāo)
-解決原有語(yǔ)法上的一些問(wèn)題或者不足
-對(duì)原有語(yǔ)法進(jìn)行增強(qiáng)
-全新的對(duì)象丈牢、全新的方法、全新的功能
-全新的數(shù)據(jù)類型和數(shù)據(jù)結(jié)構(gòu)
ES2015 let與塊級(jí)作用域
1.在這之前ES只有兩種作用域,分別是全局作用域和函數(shù)作用域,在ES2015中新增了塊級(jí)作用域耳高。
2.使用let聲明變量
3.var聲明的是全局變量,例如
var elements = [{}, {}, {}]
for (var i = 0; i < elements.length; i++){
elements[i].onclick = function () {
console.log(i)
}
}
elements[2].onclick();
// 無(wú)論是哪個(gè)elements的數(shù)組成員調(diào)用onclick()打印結(jié)果是3
const 恒量/常量
-聲明過(guò)后不允許修改
-不能改變內(nèi)存指向所踊,但是可以對(duì)其進(jìn)行添加屬性
數(shù)組的解構(gòu)
const arr = [100, 200, 300]
const [first, second, third] = arr
const [, , four] = arr
const [f1, ...rest] = arr
const [f1, f2, f3, more] = arr
const [f1, f2, f3, defaultValue = 'default value'] = arr
console.log(first, second, third) // 100 200 300
console.log(four) // 300
console.log(rest) // [200 ,300]
console.log(more) // undefined
console.log(defaultValue ) // default value
對(duì)象的解構(gòu)
const obj = {name: 'zce', age: 18}
const {name} = obj
console.log(name) // zce
避免名稱重復(fù)進(jìn)行重命名
const name = 'tom'
const {name : objName} = obj
console.log(objName) // zce
解構(gòu)方法簡(jiǎn)化代碼編寫
const {log} = console
log('test')
log('test1')
log('test2')
模板字符串
-字符串換行直接回車即可無(wú)需使用\n轉(zhuǎn)義字符
const str = `this is
my word`
-通過(guò)插值表達(dá)式嵌入對(duì)應(yīng)數(shù)值
const name = 'tom'
const msg = `Hey, ${name}`
-帶標(biāo)簽?zāi)0遄址?/p>
const name = 'tom'
const gender = true
function myTagFunc(string) {
const sex = gender ? 'man' : 'woman'
return string[0] + name + string[1] + sex + string[2]
}
const result = myTagFunc`hey, ${name} is a ${gender}.`
console.log(result) // hey, tom is a man.
-字符串?dāng)U展方法
include()泌枪、startsWith()、endsWith()
const message = 'Error: foo is not defined.'
console.log(message.startsWith('Error')) // true
console.log(message.endsWith('.')) // true
console.log(message.include('foo')) // true