ES6

hello-es6

ES6 各種新語法 入門了解 石川blue講解

視頻地址

1.ES6怎么來的

  • ECMAScript 和 JavaScript
    • ECMA 是標(biāo)準(zhǔn),JS 是實現(xiàn)
    • ECMAScript 簡稱 ECMA 或 ES
  • 歷史版本
    • 1996, ES1.0 Netscape 將 JS 提交給 ECMA 組織,ES 正式出現(xiàn)
    • 1999, ES3.0 被廣泛支持
    • 2011, ES5.1 成為 ISO 國際標(biāo)準(zhǔn)
    • 2015, ES6.0 正式發(fā)布

2.ES6兼容性

  • ES6(ES2015) 支持的環(huán)境 IE10+, Chrome, FireFox, 移動端, NodeJS

  • 解決不兼容辦法,編譯、轉(zhuǎn)換

    • 在線轉(zhuǎn)換

    • 或者提前編譯

  • Babel 中文網(wǎng)

    • Babel 入門教程 阮一峰

    • Babel 是一個 JavaScript 編譯器

    • 一個廣泛使用的轉(zhuǎn)碼器,可以將ES6代碼轉(zhuǎn)為ES5代碼,從而在現(xiàn)有環(huán)境執(zhí)行

    • 現(xiàn)在就用 ES6 編寫程序,而不用擔(dān)心現(xiàn)有環(huán)境是否支持

3.變量 let 和 常量 const

  • var 的問題
    • 可以重復(fù)聲明,沒有報錯和警告
    • 無法限制修改
    • 沒有塊級作用域, { }
  • let 和 const
    • 不能重復(fù)聲明
    • 都是塊級作用域, { } 塊內(nèi)聲明的,塊外無效
    • let 是變量,可以修改
    • const 是常量,不能修改
  • 塊級作用域舉例
    • 原來用 var 的方式,結(jié)果彈出的都是 3
    • 或者將變量 封裝到函數(shù)里,限制作用域,但比較麻煩
    • 用 let 最簡單,直接 var 改 let,解決作用域問題
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script>
        window.onload= function () {
            /*
            var aBtn = document.getElementsByTagName('input')
            for (var i=0; i < aBtn.length; i++) {
                aBtn[i].onclick = function () {
                    alert(i)
                }
            }*/
            var aBtn = document.getElementsByTagName('input')
            for (let i = 0; i < aBtn.length; i++) {
                aBtn[i].onclick = function () {
                    alert(i)
                }
            }
            /*
            var aBtn = document.getElementsByTagName('input')
            for (var i = 0; i < aBtn.length; i++) {
                // 封裝到函數(shù)里,限制作用域
                (function (i) {
                    aBtn[i].onclick = function () {
                        alert(i)
                    }
                })(i)
            }*/
        }
    </script>
</head>
<body>
    <input type="button" value="按鈕1">
    <input type="button" value="按鈕2">
    <input type="button" value="按鈕3">
</body>
</html>

4.函數(shù)-箭頭函數(shù)

  • 箭頭函數(shù),就是函數(shù)的簡寫
    • 如果只有一個參數(shù),() 可以省
    • 如果只有一個return,{}可以省
// 普通函數(shù)
function name() {

}
// 箭頭函數(shù),去掉 function, 加上 =>
() => {

}
let show1 = function () {
    console.log('abc')
}

let show2 = () => {
    console.log('abc')
}

show1() // 調(diào)用函數(shù)
show2()

let show4 = function (a) {
    return a*2
}

let show5 = a => a * 2  //簡潔,類似python lambda 函數(shù)

console.log(show4(10))
console.log(show5(10))

5.函數(shù)-參數(shù)

  • 參數(shù)擴展/展開 ...args
    • 收集剩余的參數(shù),必須當(dāng)?shù)阶詈笠粋€參數(shù)位置
    • 展開數(shù)組,簡寫,效果和直接把數(shù)組的內(nèi)容寫在這兒一樣
  • 默認(rèn)參數(shù)
function show(a, b, ...args) {
    console.log(a)
    console.log(b)
    console.log(args)
}
console.log(show(1, 2, 3, 4, 5))

let arr1 = [1, 2, 3]
let arr2 = [4, 5, 6]
let arr3 = [...arr1, ...arr2]
console.log(arr3)

function show2(a, b=5, c=8) {
    console.log(a, b, c)
}
show2(88, 12)

6.解構(gòu)賦值

    let [a, b, c] = [1, 2, 3]
    console.log(a, b, c)
    
    let {x, y, z} = {x: 1, y: 2, z: 3}
    console.log(x, y, z)
    
    let [json, arr, num, str] = [{ a: 1, b: 2 }, [1, 2, 3], 8, 'str']
    console.log(json, arr, num, str)
  • 解構(gòu)賦值
    • 左右兩個邊結(jié)構(gòu)必須一樣
    • 右邊必須是個東西
    • 聲明和賦值賦值不能分開,必須在一句話里

7.數(shù)組

  • 新增4個方法
  • map 映射 一個對一個
    let arr = [12, 5, 8]
    let result = arr.map(function (item) {
        return item*2
    })
    let result2 = arr.map(item=>item*2) // 簡寫
    console.log(result)
    console.log(result2)
    
    let score = [18, 86, 88, 24]
    let result3 = score.map(item => item >= 60 ? '及格' : '不及格')
    console.log(result3)
    
    // 結(jié)果
    [ 24, 10, 16 ]
    [ 24, 10, 16 ]
    [ '不及格', '及格', '及格', '不及格' ]
  • reduce 匯總 一堆出來一個
    • 用于比如,算個總數(shù),算個平均
    var arr = [1, 3, 5, 7]
    var result = arr.reduce(function (tmp, item, index) {
        //tmp 上次結(jié)果,item當(dāng)前數(shù),index次數(shù)1開始
        console.log(tmp, item, index)
        return tmp + item
    })
    console.log(result)
    
    var arr = [1, 3, 5, 7]
    var result = arr.reduce(function (tmp, item, index) {
        if (index != arr.length - 1) { // 不是最后一次
            return tmp + item
        } else {
            return (tmp + item)/arr.length
        }
    })
    console.log(result)  // 平均值
  • filter 過濾器 保留為true的
    var arr = [12, 4, 8, 9]
    var result = arr.filter(item => (item % 3 === 0) ? true : false)
    console.log(result)
    var result = arr.filter(item => item % 3 === 0)
    console.log(result)
    
    var arr = [
        { title: '蘋果', price: 10 },
        { title: '西瓜', price: 20 },
    ]
    var result = arr.filter(json => json.price >= 20)
    console.log(result)
  • forEach 循環(huán)迭代
var arr = [12, 4, 8, 9]
var result = arr.forEach(item => console.log(item))
var result = arr.forEach((item, index)=>console.log(item, index))

8.字符串

  • 多了兩個新方法
    • startsWith
    • endsWith
    var url = 'http://qq.com'
    console.log(url.startsWith('http'))
    console.log(url.endsWith('com'))
    // 都是 true
  • 字符串模版
    • 使用反引號,${變量}
    • 可以折行
    let a = 12
    let str1 = `asdf${a}`
    console.log(str1)
    
    let title = '標(biāo)題'
    let content = '內(nèi)容'
    let str = `<div>
    <h1>${title}</h1>
    <p>${content}</p>
    `
    console.log(str)
    <div>
    <h1>標(biāo)題</h1>
    <p>內(nèi)容</p>

9.面向?qū)ο?基礎(chǔ)

  • 原來寫法
    • 類和構(gòu)造函數(shù)一樣
    • 屬性和方法分開寫的
    // 老版本
    function User(name, pass) {
        this.name = name
        this.pass = pass
    }
    
    User.prototype.showName = function () {
        console.log(this.name)
    }
    User.prototype.showPass = function () {
        console.log(this.pass)
    }
    
    var u1 = new User('able', '1233')
    u1.showName()
    u1.showPass()
    // 老版本繼承
    function VipUser(name, pass, level) {
        User.call(this, name, pass)
        this.level = level
    }
    VipUser.prototype = new User()
    VipUser.prototype.constructor = VipUser
    VipUser.prototype.showLevel = function () {
        console.log(this.level)
    }
    
    var v1 = new VipUser('blue', '1234', 3)
    v1.showName()
    v1.showLevel()
  • 新版面向?qū)ο?
    • 有了 class 關(guān)鍵字、構(gòu)造器
    • class 里面直接加方法
    • 繼承,super 超類==父類
class User {
    constructor(name, pass) {
        this.name = name
        this.pass = pass
    }

    showName() {
        console.log(this.name)
    }
    showPass() {
        console.log(this.pass)
    }
}

var u1 = new User('able2', '111')
u1.showName()
u1.showPass()

// 新版本繼承
class VipUser extends User {
    constructor(name, pass, level) {
        super(name, pass)
        this.level = level
    }
    showLevel(){
        console.log(this.level)
    }
}

v1 = new VipUser('blue', '123', 3)
v1.showLevel()

10.面向?qū)ο髴?yīng)用

  • React

    • 用于構(gòu)建用戶界面的 JavaScript 庫

    • 組件化,一個組件就是一個 class

    • JSX == bable == browser.js

11.json

  • JSON 格式
    • JavaScript Object Notation 的縮寫,是一種用于數(shù)據(jù)交換的文本格式
    • JSON 是 JS對象 的嚴(yán)格子集
    • JSON 的標(biāo)準(zhǔn)寫法
    • 只能用雙引號
    • 所有的key都必須用雙引號包起來
  • JSON 對象
    • JSON 對象是 JavaScript 的原生對象,用來處理 JSON 格式數(shù)據(jù),有兩個靜態(tài)方法
    • JSON.parse(string) :接受一個 JSON 字符串并將其轉(zhuǎn)換成一個 JavaScript 對象。
    • JSON.stringify(obj) :接受一個 JavaScript 對象并將其轉(zhuǎn)換為一個 JSON 字符串。
var json = {a: 12, b: 5}
var str = 'hi,' + JSON.stringify(json)
var url = 'http://www.xx.com/' + encodeURIComponent(JSON.stringify(json))
console.log(str)
console.log(url)

var str = '{"a": 12, "b": 4, "c": "abc"}'
var json = JSON.parse(str)
console.log(json)
hi,{"a":12,"b":5}
http://www.xx.com/%7B%22a%22%3A12%2C%22b%22%3A5%7D
{ a: 12, b: 4, c: 'abc' }
  • 對象(object)
    • 是 JavaScript 語言的核心概念,也是最重要的數(shù)據(jù)類型
    • 對象就是一組“鍵值對”(key-value)的集合,是一種無序的復(fù)合數(shù)據(jù)集合
    • 對象的所有鍵名都是字符串, 所以加不加引號都可以
    • 如果鍵名是數(shù)值,會被自動轉(zhuǎn)為字符串
    • 對象的每一個鍵名又稱為“屬性”(property),它的“鍵值”可以是任何數(shù)據(jù)類型
    • 如果一個屬性的值為函數(shù),通常把這個屬性稱為“方法”,它可以像函數(shù)那樣調(diào)用
    • in 運算符用于檢查對象是否包含某個屬性(注意,檢查的是鍵名,不是鍵值
    • for...in循環(huán)用來遍歷一個對象的全部屬性
  • 對象 簡寫
    • key-value 一樣時可以簡寫
    • 里面函數(shù)可以簡寫, 去掉
var a = 12, b = 5
console.log({a:a, b:b})
console.log({a, b})
console.log({a, b, c:"c"})
console.log({ a, b, show(){ console.log('a') }})
{ a: 12, b: 5 }
{ a: 12, b: 5 }
{ a: 12, b: 5, c: 'c' }
{ a: 12, b: 5, show: [Function: show] }

12.Promise

  • 異步和同步
    • 異步,操作之間沒有關(guān)系,同時執(zhí)行多個操作, 代碼復(fù)雜
    • 同步,同時只能做一件事,代碼簡單
  • Promise 對象
    • 用同步的方式來書寫異步代碼
    • Promise 讓異步操作寫起來,像在寫同步操作的流程,不必一層層地嵌套回調(diào)函數(shù)
    • 改善了可讀性,對于多層嵌套的回調(diào)函數(shù)很方便
    • 充當(dāng)異步操作與回調(diào)函數(shù)之間的中介,使得異步操作具備同步操作的接口
  • Promise 也是一個構(gòu)造函數(shù)
    • 接受一個回調(diào)函數(shù)f1作為參數(shù),f1里面是異步操作的代碼
    • 返回的p1就是一個 Promise 實例
    • 所有異步任務(wù)都返回一個 Promise 實例
    • Promise 實例有一個then方法,用來指定下一步的回調(diào)函數(shù)
function f1(resolve, reject) {
  // 異步代碼...
}
var p1 = new Promise(f1);
p1.then(f2); // f1的異步操作執(zhí)行完成,就會執(zhí)行f2。
  • Promise 使得異步流程可以寫成同步流程
// 傳統(tǒng)寫法
step1(function (value1) {
  step2(value1, function(value2) {
    step3(value2, function(value3) {
      step4(value3, function(value4) {
        // ...
      });
    });
  });
});

// Promise 的寫法
(new Promise(step1))
  .then(step2)
  .then(step3)
  .then(step4);
  • Promise.all(promiseArray)方法
    • 將多個Promise對象實例包裝,生成并返回一個新的Promise實例
    • promise數(shù)組中所有的promise實例都變?yōu)閞esolve的時候,該方法才會返回
    • 并將所有結(jié)果傳遞results數(shù)組中
    • promise數(shù)組中任何一個promise為reject的話,則整個Promise.all調(diào)用會立即終止,并返回一個reject的新的promise對象
    var p1 = Promise.resolve(1),
        p2 = Promise.resolve(2),
        p3 = Promise.resolve(3);
    Promise.all([p1, p2, p3]).then(function (results) {
        console.log(results);  // [1, 2, 3]
    });
  • Promise.race([p1, p2, p3])
    • Promse.race就是賽跑的意思
    • 哪個結(jié)果獲得的快,就返回那個結(jié)果
    • 不管結(jié)果本身是成功狀態(tài)還是失敗狀態(tài)

13.generator-認(rèn)識生成器函數(shù)

  • generator 生成器函數(shù)
    • 普通函數(shù),一路到底
    • generator函數(shù),中間可以停,到哪停呢,用 yield 配合,交出執(zhí)行權(quán)
    • yield 有 放棄、退讓、退位的意思
    • 需要調(diào)用next()方法啟動執(zhí)行,需要遇到 yield 停, 踹一腳走一步
    • generator函數(shù)前面加一個 * 兩邊可以有空格,或靠近函數(shù)或function
    • 背后實際生成多個小函數(shù),實現(xiàn)走走停停
    function show() {
        console.log('a')
        console.log('b')
    }
    show() // 普通函數(shù)
    
    function *show2() {
        console.log('1')
        yield
        console.log('2')
    }
    let genObj = show2()
    genObj.next() // 1
    genObj.next() // 2
    genObj.next() // 最后了,沒有結(jié)果

14.generator-yield是啥

  • yield
    • 既可傳參,又可以返回
    • 第一個next()傳參無效,只用來啟動
  • 如果函數(shù)前漏掉 *
    • 就是普通函數(shù)
    • 如果有yield會報錯, ReferenceError: yield is not defined
    • yield 只能在Generator函數(shù)內(nèi)部使用
    function * show() {
        console.log('1')
        var a = yield
        console.log('2')
        console.log(a)
    }
    // yield 傳參
    var gen = show()
    gen.next() // 1
    gen.next() // 2 和 undefined 因為沒有傳參,yield沒有返回值
    var gen = show()
    gen.next(10) // 1 第一次執(zhí)行到y(tǒng)ield,但沒有執(zhí)行賦值
    gen.next(20) // 2 和 20
    
    function* show2() {
        console.log('1')
        yield 10
        console.log('2')
    }
    // yield 返回
    var gen = show2()
    var res1 = gen.next()
    console.log(res1) // { value: 10, done: false }
    var res2 = gen.next()
    console.log(res2)
    // { value: undefined, done: true } 最后的value需要return返回

15.generator-實例

  • Promise 適合一次讀一組
  • generator 適合邏輯性的
    // 帶邏輯-generator
    runner(function * () {
        let userData = yield $.ajax({url: 'getUserData'})
    
        if (userData.type == 'VIP') {
            let items = yield $.ajax({url: 'getVIPItems'})
        } else {
            let items = yield $.ajax({url: 'getItems'})
        }
    })
    // yield 實例,用同步方式寫異步
    server.use(function * () {
        let data = yield db.query(`select * from user_table`)
        this.body = data
    })

16.ES7 預(yù)覽

  • 數(shù)組
    • arr.includes() 數(shù)組是否包含某個東西
    • 數(shù)組的 arr.keys(), arr,entries()
    • for ... in 遍歷數(shù)組 下標(biāo) key
    • for ... of 遍歷數(shù)組 值 value, 不能用于json
    let arr = ['a', 'b', 'c']
    console.log(arr.includes(1))
    
    for (let i in arr) {
        console.log(i) // 循環(huán)的時下標(biāo) key
    }
    
    for (let i of arr) {
        console.log(i) // 循環(huán)的是值 value
    }
    for (let i of arr.keys()) {
        console.log('>'+i)
    }
    for (let [key, value] of arr.entries()) {
        console.log('>' + key + value)
    }
    
    let json = { a: 12, b: 5, c: 7 }
    for (let i in json) {
        console.log(i)
    }
  • 字符串
    • padStart()/padEnd() 指定寬度,不夠就補空格或指定字符
    console.log('=' + 'abcd'.padStart(6, '0') + '=')
    console.log('=' + 'abcd'.padEnd(6, '0') + '=')
    =00abcd=
    =abcd00=
  • 容忍度
    • [1, 2, 3,] 老版數(shù)組最后不能有逗號,新的可以有
    • 函數(shù)參數(shù)最后多的逗號也可以
  • async await
    • 和 generator yield 類似
    • generator 不可以寫成箭頭函數(shù), async 可以
async function show() {
    console.log(1)
    await
    console.log(2)
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 本文為阮一峰大神的《ECMAScript 6 入門》的個人版提純! babel babel負(fù)責(zé)將JS高級語法轉(zhuǎn)義,...
    Devildi已被占用閱讀 2,128評論 0 4
  • 簡介 基本概念 Generator函數(shù)是ES6提供的一種異步編程解決方案,語法行為與傳統(tǒng)函數(shù)完全不同。本章詳細(xì)介紹...
    呼呼哥閱讀 1,135評論 0 4
  • 在此處先列下本篇文章的主要內(nèi)容 簡介 next方法的參數(shù) for...of循環(huán) Generator.prototy...
    醉生夢死閱讀 1,486評論 3 8
  • [TOC] 參考阮一峰的ECMAScript 6 入門參考深入淺出ES6 let和const let和const都...
    郭子web閱讀 1,914評論 0 1
  • 轉(zhuǎn)載請注明出處 原文連接 http://blog.huanghanlian.com/article/5c7aa6c...
    深沉的簡單閱讀 1,947評論 0 40

友情鏈接更多精彩內(nèi)容