在B站跟着石川blue老師快速學完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 正式發佈
2.ES6兼容性
-
ES6(ES2015) 支持的環境 IE10+, Chrome, FireFox, 移動端, NodeJS
-
解決不兼容辦法,編譯、轉換
- 在線轉換
- 或者提前編譯
-
- Babel 入門教程 阮一峯
- Babel 是一個 JavaScript 編譯器
- 一個廣泛使用的轉碼器,可以將ES6代碼轉爲ES5代碼,從而在現有環境執行
- 現在就用 ES6 編寫程序,而不用擔心現有環境是否支持
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 循環迭代
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.面向對象應用
- React
- 用於構建用戶界面的 JavaScript 庫
- 組件化,一個組件就是一個 class
- JSX == bable == browser.js
11.json
-
JSON 格式
- JavaScript Object Notation 的縮寫,是一種用於數據交換的文本格式
- JSON 是 JS對象 的嚴格子集
- JSON 的標準寫法
- 只能用雙引號
- 所有的key都必須用雙引號包起來
-
JSON 對象
- JSON 對象是 JavaScript 的原生對象,用來處理 JSON 格式數據,有兩個靜態方法
- 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循環用來遍歷一個對象的全部屬性
-
對象 簡寫
- 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
-
異步和同步
- 異步,操作之間沒有關係,同時執行多個操作, 代碼複雜
- 同步,同時只能做一件事,代碼簡單
-
Promise 對象
- 用同步的方式來書寫異步代碼
- Promise 讓異步操作寫起來,像在寫同步操作的流程,不必一層層地嵌套回調函數
- 改善了可讀性,對於多層嵌套的回調函數很方便
- 充當異步操作與回調函數之間的中介,使得異步操作具備同步操作的接口
-
Promise 也是一個構造函數
- 接受一個回調函數f1作爲參數,f1裏面是異步操作的代碼
- 返回的p1就是一個 Promise 實例
- 所有異步任務都返回一個 Promise 實例
- Promise 實例有一個then方法,用來指定下一步的回調函數
function f1(resolve, reject) {
// 異步代碼...
}
var p1 = new Promise(f1);
p1.then(f2); // f1的異步操作執行完成,就會執行f2。
- Promise 使得異步流程可以寫成同步流程
// 傳統寫法
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實例都變爲resolve的時候,該方法纔會返回
- 並將所有結果傳遞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就是賽跑的意思
- 哪個結果獲得的快,就返回那個結果
- 不管結果本身是成功狀態還是失敗狀態
13.generator-認識生成器函數
- generator 生成器函數
- 普通函數,一路到底
- generator函數,中間可以停,到哪停呢,用 yield 配合,交出執行權
- yield 有 放棄、退讓、退位的意思
- 需要調用next()方法啓動執行,需要遇到 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 第一次執行到yield,但沒有執行賦值
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) // 循環的時下標 key
}
for (let i of arr) {
console.log(i) // 循環的是值 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)
}
我是樂樂呀,感謝您的閱讀。如果您覺得不錯,那就點個贊吧,您的支持是我最大的動力。謝謝😜