hello-es6
ES6 各種新語法 入門了解 石川blue講解
視頻地址
1.ES6怎么來的
- ECMAScript 和 JavaScript
- ECMA 是標準酬滤,JS 是實現
- ECMAScript 簡稱 ECMA 或 ES
- 歷史版本
- 1996, ES1.0 Netscape 將 JS 提交給 ECMA 組織签餐,ES 正式出現
- 1999, ES3.0 被廣泛支持
- 2011, ES5.1 成為 ISO 國際標準
- 2015, ES6.0 正式發(fā)布
2.ES6兼容性
ES6(ES2015) 支持的環(huán)境 IE10+, Chrome, FireFox, 移動端, NodeJS
-
解決不兼容辦法,編譯盯串、轉換
在線轉換
或者提前編譯
-
Babel 是一個 JavaScript 編譯器
一個廣泛使用的轉碼器氯檐,可以將ES6代碼轉為ES5代碼,從而在現有環(huán)境執(zhí)行
現在就用 ES6 編寫程序体捏,而不用擔心現有環(huán)境是否支持
3.變量 let 和 常量 const
- var 的問題
- 可以重復聲明冠摄,沒有報錯和警告
- 無法限制修改
- 沒有塊級作用域, { }
- let 和 const
- 不能重復聲明
- 都是塊級作用域, { } 塊內聲明的几缭,塊外無效
- let 是變量河泳,可以修改
- const 是常量,不能修改
- 塊級作用域舉例
- 原來用 var 的方式年栓,結果彈出的都是 3
- 或者將變量 封裝到函數里拆挥,限制作用域,但比較麻煩
- 用 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++) {
// 封裝到函數里惰瓜,限制作用域
(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.函數-箭頭函數
- 箭頭函數,就是函數的簡寫
- 如果只有一個參數汉矿,() 可以省
- 如果只有一個return崎坊,{}可以省
// 普通函數
function name() {
}
// 箭頭函數,去掉 function负甸, 加上 =>
() => {
}
let show1 = function () {
console.log('abc')
}
let show2 = () => {
console.log('abc')
}
show1() // 調用函數
show2()
let show4 = function (a) {
return a*2
}
let show5 = a => a * 2 //簡潔流强,類似python lambda 函數
console.log(show4(10))
console.log(show5(10))
5.函數-參數
- 參數擴展/展開 ...args
- 收集剩余的參數,必須當到最后一個參數位置
- 展開數組呻待,簡寫,效果和直接把數組的內容寫在這兒一樣
- 默認參數
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.解構賦值
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)
- 解構賦值
- 左右兩個邊結構必須一樣
- 右邊必須是個東西
- 聲明和賦值賦值不能分開队腐,必須在一句話里
7.數組
- 新增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)
// 結果
[ 24, 10, 16 ]
[ 24, 10, 16 ]
[ '不及格', '及格', '及格', '不及格' ]
- reduce 匯總 一堆出來一個
- 用于比如蚕捉,算個總數,算個平均
var arr = [1, 3, 5, 7]
var result = arr.reduce(function (tmp, item, index) {
//tmp 上次結果柴淘,item當前數迫淹,index次數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 = '標題'
let content = '內容'
let str = `<div>
<h1>${title}</h1>
<p>${content}</p>
`
console.log(str)
<div>
<h1>標題</h1>
<p>內容</p>
9.面向對象-基礎
- 原來寫法
- 類和構造函數一樣
- 屬性和方法分開寫的
// 老版本
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()
- 新版面向對象
- 有了 class 關鍵字为严、構造器
- 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.面向對象應用
-
用于構建用戶界面的 JavaScript 庫
組件化,一個組件就是一個 class
JSX == bable == browser.js
11.json
- JSON 格式
- JavaScript Object Notation 的縮寫第股,是一種用于數據交換的文本格式
- JSON 是 JS對象 的嚴格子集
- JSON 的標準寫法
- 只能用雙引號
- 所有的key都必須用雙引號包起來
- JSON 對象
- JSON 對象是 JavaScript 的原生對象应民,用來處理 JSON 格式數據,有兩個靜態(tài)方法
- JSON.parse(string) :接受一個 JSON 字符串并將其轉換成一個 JavaScript 對象夕吻。
- JSON.stringify(obj) :接受一個 JavaScript 對象并將其轉換為一個 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 語言的核心概念,也是最重要的數據類型
- 對象就是一組“鍵值對”(key-value)的集合涉馅,是一種無序的復合數據集合
- 對象的所有鍵名都是字符串, 所以加不加引號都可以
- 如果鍵名是數值归园,會被自動轉為字符串
- 對象的每一個鍵名又稱為“屬性”(property),它的“鍵值”可以是任何數據類型
- 如果一個屬性的值為函數稚矿,通常把這個屬性稱為“方法”庸诱,它可以像函數那樣調用
- in 運算符用于檢查對象是否包含某個屬性(注意,檢查的是鍵名晤揣,不是鍵值
- for...in循環(huán)用來遍歷一個對象的全部屬性
- 對象 簡寫
- key-value 一樣時可以簡寫
- 里面函數可以簡寫, 去掉
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
- 異步和同步
- 異步桥爽,操作之間沒有關系,同時執(zhí)行多個操作碉渡, 代碼復雜
- 同步聚谁,同時只能做一件事,代碼簡單
- Promise 對象
- 用同步的方式來書寫異步代碼
- Promise 讓異步操作寫起來滞诺,像在寫同步操作的流程形导,不必一層層地嵌套回調函數
- 改善了可讀性环疼,對于多層嵌套的回調函數很方便
- 充當異步操作與回調函數之間的中介,使得異步操作具備同步操作的接口
- Promise 也是一個構造函數
- 接受一個回調函數f1作為參數朵耕,f1里面是異步操作的代碼
- 返回的p1就是一個 Promise 實例
- 所有異步任務都返回一個 Promise 實例
- Promise 實例有一個then方法炫隶,用來指定下一步的回調函數
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數組中所有的promise實例都變?yōu)閞esolve的時候,該方法才會返回
- 并將所有結果傳遞results數組中
- promise數組中任何一個promise為reject的話处嫌,則整個Promise.all調用會立即終止栅贴,并返回一個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就是賽跑的意思
- 哪個結果獲得的快,就返回那個結果
- 不管結果本身是成功狀態(tài)還是失敗狀態(tài)
13.generator-認識生成器函數
- generator 生成器函數
- 普通函數熏迹,一路到底
- generator函數檐薯,中間可以停,到哪停呢注暗,用 yield 配合坛缕,交出執(zhí)行權
- yield 有 放棄、退讓捆昏、退位的意思
- 需要調用next()方法啟動執(zhí)行赚楚,需要遇到 yield 停, 踹一腳走一步
- generator函數前面加一個 * 兩邊可以有空格,或靠近函數或function
- 背后實際生成多個小函數骗卜,實現走走停停
function show() {
console.log('a')
console.log('b')
}
show() // 普通函數
function *show2() {
console.log('1')
yield
console.log('2')
}
let genObj = show2()
genObj.next() // 1
genObj.next() // 2
genObj.next() // 最后了宠页,沒有結果
14.generator-yield是啥
- yield
- 既可傳參,又可以返回
- 第一個next()傳參無效膨俐,只用來啟動
- 如果函數前漏掉 *
- 就是普通函數
- 如果有yield會報錯勇皇, ReferenceError: yield is not defined
- yield 只能在Generator函數內部使用
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 預覽
- 數組
- arr.includes() 數組是否包含某個東西
- 數組的 arr.keys(), arr,entries()
- for ... in 遍歷數組 下標 key
- for ... of 遍歷數組 值 value, 不能用于json
let arr = ['a', 'b', 'c']
console.log(arr.includes(1))
for (let i in arr) {
console.log(i) // 循環(huán)的時下標 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,] 老版數組最后不能有逗號乳愉,新的可以有
- 函數參數最后多的逗號也可以
- async await
- 和 generator yield 類似
- generator 不可以寫成箭頭函數兄淫, async 可以
async function show() {
console.log(1)
await
console.log(2)
}