es6語(yǔ)法
*let和const
1.{}包住里面就是塊作用域,let只在塊作用域生效
2.let不能重復(fù)定義相同變量
3.const是常量,不能修改,定義后是只讀不能修改。
4.const聲明的時(shí)候必須賦值,也有塊作用域。
5.const如果定義成對(duì)象,就可以修改的,對(duì)象是引用類型(返回值是存儲(chǔ)內(nèi)存的指針,指針是不變的,但是對(duì)象本身是可以變的)。
*解構(gòu)賦值
左邊一個(gè)結(jié)構(gòu),右邊一個(gè)結(jié)構(gòu),然后左右一一對(duì)應(yīng)進(jìn)行賦值
數(shù)組解構(gòu)賦值
{
let a,b,rest;
[a,b] = [1,2];
console.log(a,b) //1 2
}
{
let a,b,rest;
[a,b,...rest] = [1,2,3,4,5,6];
console.log(a,b,rest) //1 2 [3,4,5,6]
}
{
let a,b,c,rest;
[a,b,c=3] = [1,2];
console.log(a,b) //1 2 如果不定義c給默認(rèn)值3,就等于定義沒賦值undefined
}
對(duì)象解構(gòu)賦值
{
let a,b;
({a,b}={a:1,b:2})
console.log(a,b) //1 2
}
字符串解構(gòu)賦值
布爾值解構(gòu)賦值
函數(shù)參數(shù)解構(gòu)賦值
數(shù)值解構(gòu)賦值
應(yīng)用場(chǎng)景
適合變量交換
數(shù)組型
{
let a =1;
let b=2;
[a,b] = [b,a]
console.log(a,b) //2,1
}
{
function f(){
retrun [1,2]
}
let a,b
[a,b]=f()
console.log(a,b) //簡(jiǎn)單接收返回值
}
{
function f(){
renturn [1,2,3,4,5]
}
let a,b,c
[a,,,b] =f()
console.log(a,b) // 1 4 按順序匹配用, 分割 。用來選擇性接收某幾個(gè)變量
}
{
function f(){
renturn [1,2,3,4,5]
}
let a,b,c
[a,...b] =f()
console.log(a,b) // 1 [2,3,4,5] 這種是不知道返回的數(shù)組長(zhǎng)度是多少,我只關(guān)心第一個(gè),其他就返回一個(gè)數(shù)組,想用就遍歷,就等于取出第一個(gè)元素,其他放在一個(gè)數(shù)組里面
}
對(duì)象型
{
let o = {p:42,q:true}
let {p,q} = o
console.log(p,q) //42 true
}
{
let {a=10,b=5} = {a:3}
console.log(a,b) // 3 5
}
{
let metaData = {
title:'abc',
test:[{
title:'test',
desc:'description'
}]
}
let {title:esTitle,test:[{title:cnTitle}]} = metaData;
console.log(esTitle,cnTitle) // abc test
}
*正則擴(kuò)展
正則新增特性
構(gòu)造函數(shù)的變化
//es5
let regex new RegExp('xyz','i') //i忽略大小寫 兩個(gè)參數(shù)
let regx2 = new RegExp(/xyz/i) //一個(gè)參數(shù)
//es6
let regx3 = new RegExp(/xyz/ig,'i') //es6第二個(gè)參數(shù)會(huì)覆蓋第一個(gè)參數(shù)所制定
的修飾符
console.log(regex3.flags)//獲取當(dāng)前的修飾符
正則方法的擴(kuò)展
u修飾符
{
console.log('u-1',/^\uD83D/.test('\uD83D\uDC2A')) // true 當(dāng)成兩個(gè)字母
console.log('u-1',/^\uD83D/u.test('\uD83D\uDC2A'))//false u會(huì)把2個(gè)字符當(dāng)作一個(gè)字符
}
y修飾符
{
let s = 'bbb_bb_b'
let a1 = /b+/g
let a2 = /b+/y
console.log('one',a1.exec(s),a2.exec(s))
console.log('two',a1.exec(s),a2.exec(s))
//g是從上一次匹配的位置再尋找,不強(qiáng)調(diào)必須是匹配下一個(gè)字符的開始匹配,中間任何位置匹配上都算
//y是一定要匹配到下一個(gè)字符也匹配到才算
}
s修飾符
*字符串拓展
新增特訓(xùn)
Unicode表示法
console.log('a',`\u0061`)
console.log('a',`\u20BB7`) //這個(gè)會(huì)打印亂碼和7 因?yàn)榻M合超過0XFFFF字節(jié)
console.log('a',`\u{20BB7}`)
遍歷接口
let str = '\u{20bb7}abc'
for(let code of str){
console.log('es6',code)
}
模版字符串
let name='list'
let info = 'hello world'
let m = `i am ${name},${info}`
新增方法10種
//判斷字符串種是否包含某些字符
let str = 'string'
console.log('includes',str.includes('r')) //true
//判斷字符串是不是以某個(gè)字符為起始或者終始
let str = 'string'
console.log('start',str.startsWith('str')) //true
console.log('end',str.endsWith('ng')) //true
//復(fù)制字符串
let str = 'abc'
console.log(str.repeat(2)) //abcabc
//補(bǔ)位(可用于日期選擇)
//向前補(bǔ)
console.log('1'.padStart(2,'0')) //意思就是要2位,不夠用0補(bǔ),輸出01
//向后補(bǔ)
console.log('1'.padEnd(2,'0')) //意思就是要2位,不夠用0補(bǔ),輸出10
//raw \轉(zhuǎn)義 就是又加一個(gè)\
console.log(String.raw`Hi\n${1+2}`)
console.log(`Hi\n${1+2}`)
//標(biāo)簽?zāi)0?br>
參考https://www.cnblogs.com/sminocence/p/6832331.html
參考http://m.itdecent.cn/p/c65b9930dd11
*數(shù)值擴(kuò)展
數(shù)值處理新增特性
1.新增方法
console.log(Number.isFinite(15)) //判斷這個(gè)數(shù)是不是無窮大
console.log(NUmber.isNaN(NaN)) //判斷這個(gè)數(shù)是不是一個(gè)數(shù)
console.log(Number.isInteger(25))//判斷這個(gè)數(shù)是不是一個(gè)整數(shù)
console.log(Math.trnc(4.1))//取整 小數(shù)會(huì)刪掉
console.log(Math.sign(-5))//判斷是否正負(fù)數(shù)或者0
2.方法調(diào)整
數(shù)組擴(kuò)展
數(shù)組新增特性
Array.form
//把一個(gè)集合轉(zhuǎn)換成真正的數(shù)組
<p>你好</p>
<p>你好1</p>
<p>你好2</p>
{
let p = document.querySelectorAll('p')
let pArr = Array.from(p)
pArr.forEach(function(item){
console.log(item.texrContent)
})
}
{
//第二個(gè)用法 可以遍歷第一個(gè)參數(shù)的數(shù)組,類似map方法
console.log(Array.from([1,3,4],function(item){return item*2}))
}
Array.of
//把一組數(shù)據(jù)變量,轉(zhuǎn)換成數(shù)據(jù)類型
let arr = Array.of(3,9,11,20,30)
console.log(arr)//[3,9,11,20,30]
copyWithin
{
console.log([1,2,3,4,5].copyWithin(0,3,4)) 1參數(shù):從那個(gè)位置開始替換 2:從那個(gè)位置開始讀取位置 3:從那個(gè)位置截止 //[4,2,3,4,5]
}
find\findIndex
{
//查找數(shù)組中有沒有一個(gè)元素大于3的,找出第一個(gè)滿足就停止查找
console.log([1,2,3,4,5,6].find(function(item){ return item>3})) //4
}
{
//查找數(shù)組中有沒有一個(gè)元素大于3的,找出第一個(gè)滿足返回下標(biāo)就停止查找
console.log([1,2,3,4,5,6].findIndex(function(item){ return item>3})) //3
}
fill
console.log([1,'a',undefined].fill(7))//把數(shù)組里面的每個(gè)值變成7
//['a','b','c'].fill(7,1,3) 后面2個(gè)參數(shù)是起始和結(jié)束位置,從第一個(gè)開始換一直到第三個(gè)
entries\keys\values
//keys返回下標(biāo)
{
for(let index of ['1','c','ks'].keys()){
console.log(index)
}
}
//values返回值 (有兼容問題這個(gè))
{
for(let value of ['1','c','ks'].values()){
console.log(value)
}
}
//entries返回下標(biāo)和值
{
for(let [index,value] of ['1','c','ks'].entries()){
console.log(value,index)
}
}
includes
//查找一個(gè)數(shù)組是否包含某個(gè)元素
{
console.log([1,2,NaN].includes(1)) //true
}
*函數(shù)擴(kuò)展
函數(shù)新增特性
參數(shù)默認(rèn)值
{
//默認(rèn)值變量后面不能有再有沒有默認(rèn)值的變量?。。。。。? function test(x,y='world'){
console.log(x,y)
}
test('hello')
}
rest參數(shù)
//把一系列的參數(shù)轉(zhuǎn)換成一個(gè)數(shù)組
//作用就是把你不確定有多少個(gè)參數(shù),最終把你輸入的參數(shù)轉(zhuǎn)換成一個(gè)數(shù)組
//注意rest參數(shù)后面不能再有參數(shù),不然會(huì)報(bào)錯(cuò)
{
function test3(...arg){
for(let v of arg){
console.log(v)
}
}
test3(1,2,3,4,5,'a')
}
擴(kuò)展運(yùn)算符
{
//把一個(gè)數(shù)組拆開
console.log(...[1,2,3])
}
箭頭函數(shù)
{
//第一部分函數(shù)名,函數(shù)參數(shù)(如果沒有參數(shù)就給一個(gè)()),函數(shù)返回值
let arrow = v => v*2
console.log(arrow(3)) //6
}
this綁定
尾調(diào)用
//提升性能
{
function tail(x){
console.log('tail',x)
}
funciton fx(x){
return tail(x)
}
fx(123)
}
*對(duì)象擴(kuò)展
函數(shù)新增特性
簡(jiǎn)潔表示法
{
let o = 1
let l =2
let es5 = {
o:o,
k:k
}
let es6 = {
o,
k
}
}
{
let es5_method = {
hello:function(){
console.log('hello')
}
}
let es6_method = {
hello(){
console.log('hello')
}
}
}
屬性表達(dá)式
{
let a = 'b'
let es5_obj={
a:'c',
b:'c'
}
//[]相當(dāng)于傳了個(gè)變量過去,比如像生成一個(gè)對(duì)象,k值可以變化的 就挺有用的
let es6_obj = {
[a]:'c'
}
console.log(es6_obj) // b:c
}
擴(kuò)展運(yùn)算符
{
let {a,b,...c} = {a:'test',b:'kill',c:'ddd',d:'ccc'}
//a對(duì)應(yīng)a b對(duì)應(yīng)b c對(duì)應(yīng)后面的c,d
//如果后面還有都統(tǒng)統(tǒng)賦值給c
}
Object新增方法
//新增API
//和===一樣
console.log('字符串',Object.is('abc','abc'),'abc'==='abc')
console.log('數(shù)組',Object.is([],[]),[]===[]) //數(shù)組是引用類型,地址指向不一樣,所以打印是 false
console.log('拷貝',Object.assign({a:'a'},{b:'b'})) //就會(huì)合并在一起,淺拷貝
//遍歷
let test = {k:123,o:456}
for(let [key,value] of Object.entries(test)){
console.log([key,value])
}
*Symbol
Symbol的概念
提供一個(gè)獨(dú)一無二的值
{
//聲明
let a1 = Symbol();
let a2 = Symbol();
console.log(a1===a2) //false
let a3 = Symbol.for('a3')
let a4 = Symbol.for('a3') //先去全局找 有就引用,沒就創(chuàng)建一個(gè)獨(dú)一無二的值
console.log(a3===a4) //true
}
Symbol的作用
{
//可以生成唯一的,不會(huì)重復(fù),就算重寫也覆蓋不到。
//注意,如果用Symbol定義,用for of 是取不到的,需要用Object.getOwnPropertySymbols()
let a1 = Symbol.for('abc')
let obj = {
[a1]: '123',
'abc': 345,
'c': 456
}
console.log(obj) //abc:345,c:456,Symbol(abc):123
Object.getOwnPropertySymbols(obj).forEach*function(item){
console.log(obj[item]) //只能拿到k值是Symbol的
}
Reflect.ownKeys(obj) //能拿到Symbol和非Symbol的值 也是返回?cái)?shù)組,可以直接使用forEach
}
*數(shù)據(jù)結(jié)構(gòu)
Set的用法(數(shù)組去理解,但是不能重復(fù))
{
let list = new Set();
list.add(5)
list.add(7)//在Set里面增加?xùn)|西要用add
console.log(list.size) //在Set里面的長(zhǎng)度,理解是數(shù)組的length
}
{
let arr = [1,2,3,4,5]
let list = new Set(arr) //標(biāo)示list是轉(zhuǎn)換一個(gè)Set的數(shù)據(jù)類型集合
}
{
let list = new Set()
lista.add(1)
lista.add(2)
lista.add(1)
console.log(list) //最后一個(gè)1不會(huì)存在,去重了
let arr = [1,2,3,1,2]
let list2 = new Set(arr)
console.log(list2) //1.2.3 不會(huì)對(duì)數(shù)據(jù)轉(zhuǎn)換,如果[1,2,3,1,'2'] 字符串2不會(huì)過濾
}
{
let arr = ['add','delete','clear','has']
let list = new Set(arr)
console.log('has',list.has('add')) //true 判斷集合是否含有add
console.log('delete',list.delete('add')) //{'delete','clear','has'}
list.clear()
console.log('list',list)//清空所有了
}
//遍歷
{
let arr = ['add','delete','clear','has']
let list = new Set(arr)
//輸出都一樣 都是名稱
for(let key of list.keys()){
console.log(key)
}
//輸出都一樣 都是名稱
for(let value of list.values()){
console.log(value)
}
}
WeakSet的用法 (弱引用)
//支持的數(shù)據(jù)類型區(qū)別,WeakSet只能是對(duì)象,弱引用,不會(huì)檢測(cè)有沒有在其他地方用過,不會(huì)改變?cè)赶虻刂?{
let weakList = new WeakSet()
let arg = {}
weakList.add(arg)
console.log(weakList) // {}
}
Map的用法(Object去理解,一個(gè)k,v值)
{
let map = new Map()
let arr = ['123']
map.set(arr,456) //添加元素 map的k可以是任何的數(shù)據(jù)類型
console.log(map.get(arr)) //456
console.log(map) // ['123'] => 456
}
{
//第二種定義方式
let map = new Map([['a',123],['b',456]])
console.log(map)
map.size //獲取長(zhǎng)度
map.delete('a') //刪除
map.clear() //清空
}
WeakMap的用法 (弱引用)
//和WeakSet一樣
JSON 和 Map的相同點(diǎn)就是 key,value的方式存儲(chǔ)的, 而JSON精確的說鍵值只支持String(也可以存數(shù)值,但是數(shù)值存進(jìn)去,取出來還是String),Map鍵值都可以存儲(chǔ)對(duì)象.
鍵值對(duì)的存儲(chǔ)結(jié)構(gòu)你自己也可以寫.
最后總結(jié):
filter方法是對(duì)原數(shù)組進(jìn)行過濾篩選,產(chǎn)生一個(gè)新的數(shù)組對(duì)象
map方法對(duì)元素中的元素進(jìn)行加工處理,產(chǎn)生一個(gè)新的數(shù)組對(duì)象。
Map與Array的對(duì)比
//數(shù)據(jù)結(jié)構(gòu)橫向?qū)Ρ?,增,查,改,刪
{
let map = new Map()
let array = []
//增
map.set('t',1)
array.push({t:1})
console.info(map,array)
//查
let map_exist = map.has('t')
let array_exist = array.find(item=>item.t)
console.info(map_exist,array_exist)
//改
map.set('t',2)
array.forEach(item=>item.t?item.t=2:'')
console.info(map_exist,array_exist)
//刪
map.delete('t')
let index = array.findIndex(item=>item.t)
array.splice(index,1)
}
Set與Array的對(duì)比
{
let set = new Set()
let array=[]
//增
set.add({t:1})
array.push({t:1})
//查
let set_exist = set.has({t:1})
let array_exist = array.find(item=>item.t)
//改
set.forEach(item=>item.t?item.t=2:'')
array_exist.forEach(item=>item.t?item.t=2:'')
//刪
set.forEach(item=>item.t?set.delete(item):'')
let index = array.findIndex(item=>item.t)
array.splice(index,1)
}
Map與Object的對(duì)比
Set與Object的對(duì)比
{
//map,set,object對(duì)比
let item = {t:1}
let map = new Map()
let set = new Set()
let obj = {}
//增
map.set('t',1)
set.add(item)
obj['t'] = 1
//查
map.has('t')
set.has(item)
't' in obj
//改
map.set('t',2)
item.t = 2
obj['t'] = 2
//刪除
map.delete('t')
set.delete(item)
delete obj['t']
}
//優(yōu)先使用map,如果對(duì)數(shù)據(jù)要求比較高唯一性考慮set
*Proxy和Reflect
Proxy和Reflect的概念
{
//有一個(gè)類似供應(yīng)商的原始數(shù)據(jù)
let obj = {
time:'2017-03-11',
name:'net',
_r:123
}
//然后通過new Proxy先生成一個(gè)對(duì)象,這個(gè)對(duì)象是映射obj,然后中間做一些操作,最后用戶訪問的是monitor,不管用戶是讀取還是設(shè)置monitor對(duì)象,最終由這個(gè)Proxy傳遞給obj對(duì)象
let monitor = new Proxy(obj,{
//攔截對(duì)象屬性的讀取
get(target,key){
return target[key].replace('2017','2018') //不管你讀取我什么屬性,我要把屬性所有的2017值替換成2018
},
//攔截對(duì)象設(shè)置屬性
set(target,key,value){
if(key === 'name'){
return target[key] =value
}else{
return target[key]
}//只允許修改name屬性
},
//攔截key in object操作
has(target,key){
if(key==='name'){
return target[key]
}else{
return false
}
},
//攔截刪除
deleteProperty(target,key){
if(key.indexOf('_')>-1){
delete target[key];
return true
}else{
return target[key]
}
},
//攔截Object.keys,Object.getOwnPropertySymbols,Object.getOwnPropertyNames
ownKeys(target){
return Object.keys(target).filter(item=>item!='time')
}
})
//讀取操作 monitor.time
console.log('get',monitor.time)
//設(shè)置操作
monitor.time = '2018'
console.log('set',monitor.time)
//攔截in
console.log('has','name' in monitor)
//刪除
delete monitor.time
console.log('delete',monitor)
//循環(huán)
console.log('ownKeys',Object.keys(monitor))
}
{
let obj = {
time:'2017-03-11',
name:'net',
_r:123
}
Reflect.get(obj,'time')
Reflect.set('obj','name','mukewang')
Reflect.has(obj,'name')
}
Proxy和Reflect的適用場(chǎng)景
{
//對(duì)數(shù)據(jù)校驗(yàn),比如手機(jī)號(hào)格式是否正確
function validator(target,validator){
return new Proxy(target,{
_validator:validator,
set(target,key,value,proxy){
if(target.hasOwnProperty(key)){
let va = this._validator[key];
if(!!va(value)){
return Reflect. set(target,key,value,proxy)
}else{
throw Error(不能說何止`${key}` 到 `${value}`)
}
}else{
throw Error(`${key}` 不存在)
}
}
})
}
}
*類
類的概念
基本語(yǔ)法
{
//基本定義和生成實(shí)例
class Parent{
constructor(name='mukewang'){
this.name = name
}
}
let v_parent = new Parent('v')
console.log(v_parent)
}
類的繼承
{
//繼承
class Parent{
constructor(name='mukewang'){
this.name = name
}
}
class Child extends Parent{
}
console.log(new Child())
}
{
//繼承傳遞參數(shù)
class Parent{
constructor(name='mukewang'){
this.name = name
}
}
class Child extends Parent{
constructor(name='child'){
super(name) //覆蓋父類 完成子類向父類傳遞參數(shù), 這個(gè)一定要放在構(gòu)造函數(shù)的第一行
}
}
console.log(new Child())
}
靜態(tài)方法
{
//靜態(tài)方法 概念:是通過類去調(diào)用,而不是通過實(shí)例去調(diào)用
class Parent{
constructor(name='mukewang'){
this.name = name
}
static tell(){
console.log('tell')
}
}
Parent.tell()
}
靜態(tài)屬性
{
//靜態(tài)屬性
class Parent{
constructor(name='mukewang'){
this.name = name
}
}
Parent.type = 'test'
console.log(Parent.type) //不用實(shí)例調(diào)用,用類調(diào)用
}
geter
{
//getter,setter
class Parent{
constructor(name='mukewang'){
this.name = name
}
//定義一個(gè)實(shí)例里的屬性
get longName(){
return 'mk' + this.name
}
set longName(value){
this.name = value
}
}
let v = new Parent()
console.log('getter',v.longName) //mkmukewang
v.longName = 'hello'
console.log('setter',v.longName) //mkhello
}
setter
*Promise
什么是異步
Promise的作用
Promise的基本用法
{
// 基本定義
let ajax=function(callback){
console.log('執(zhí)行');
setTimeout(function () {
callback&&callback.call()
}, 1000);
};
ajax(function(){
console.log('timeout1');
})
}
{
//基本操作
let ajax=function(){
console.log('執(zhí)行2');
return new Promise(function(resolve,reject){
setTimeout(function () {
resolve()
}, 1000);
})
};
ajax().then(function(){
console.log('promise','timeout2');
})
}
{
//多個(gè).then用法
let ajax=function(){
console.log('執(zhí)行3');
return new Promise(function(resolve,reject){
setTimeout(function () {
resolve()
}, 1000);
})
};
ajax()
.then(function(){
return new Promise(function(resolve,reject){
setTimeout(function () {
resolve()
}, 2000);
});
})
.then(function(){
console.log('timeout3');
})
}
{
//捕獲錯(cuò)誤
let ajax=function(num){
console.log('執(zhí)行4');
return new Promise(function(resolve,reject){
if(num>5){
resolve()
}else{
throw new Error('出錯(cuò)了')
}
})
}
ajax(6).then(function(){
console.log('log',6);
}).catch(function(err){
console.log('catch',err);
});
ajax(3).then(function(){
console.log('log',3);
}).catch(function(err){
console.log('catch',err);
});
}
高級(jí)用法
一、Pomise.all的使用
Promise.all可以將多個(gè)Promise實(shí)例包裝成一個(gè)新的Promise實(shí)例。同時(shí),成功和失敗的返回值是不同的,成功的時(shí)候返回的是一個(gè)結(jié)果數(shù)組,而失敗的時(shí)候則返回最先被reject失敗狀態(tài)的值。
具體代碼如下:
let p1 = new Promise((resolve, reject) => {
resolve('成功了')
})
let p2 = new Promise((resolve, reject) => {
resolve('success')
})
let p3 = Promse.reject('失敗')
Promise.all([p1, p2]).then((result) => {
console.log(result) //['成功了', 'success']
}).catch((error) => {
console.log(error)
})
Promise.all([p1,p3,p2]).then((result) => {
console.log(result)
}).catch((error) => {
console.log(error) // 失敗了,打出 '失敗'
})
Promse.all在處理多個(gè)異步處理時(shí)非常有用,比如說一個(gè)頁(yè)面上需要等兩個(gè)或多個(gè)ajax的數(shù)據(jù)回來以后才正常顯示,在此之前只顯示loading圖標(biāo)。
代碼模擬:
let wake = (time) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(`${time / 1000}秒后醒來`)
}, time)
})
}
let p1 = wake(3000)
let p2 = wake(2000)
Promise.all([p1, p2]).then((result) => {
console.log(result) // [ '3秒后醒來', '2秒后醒來' ]
}).catch((error) => {
console.log(error)
})
需要特別注意的是,Promise.all獲得的成功結(jié)果的數(shù)組里面的數(shù)據(jù)順序和Promise.all接收到的數(shù)組順序是一致的,即p1的結(jié)果在前,即便p1的結(jié)果獲取的比p2要晚。這帶來了一個(gè)絕大的好處:在前端開發(fā)請(qǐng)求數(shù)據(jù)的過程中,偶爾會(huì)遇到發(fā)送多個(gè)請(qǐng)求并根據(jù)請(qǐng)求順序獲取和使用數(shù)據(jù)的場(chǎng)景,使用Promise.all毫無疑問可以解決這個(gè)問題。
二、Promise.race的使用
顧名思義,Promse.race就是賽跑的意思,意思就是說,Promise.race([p1, p2, p3])里面哪個(gè)結(jié)果獲得的快,就返回那個(gè)結(jié)果,不管結(jié)果本身是成功狀態(tài)還是失敗狀態(tài)。
let p1 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('success')
},1000)
})
let p2 = new Promise((resolve, reject) => {
setTimeout(() => {
reject('failed')
}, 500)
})
Promise.race([p1, p2]).then((result) => {
console.log(result)
}).catch((error) => {
console.log(error) // 打開的是 'failed'
})
原理是挺簡(jiǎn)單的,但是在實(shí)際運(yùn)用中還沒有想到什么的使用場(chǎng)景會(huì)使用到。
*lterator和for...of循環(huán)
什么是lterator接口
lterator的基本用法
{
let arr=['hello','world'];
let map=arr[Symbol.iterator]();
console.log(map.next());
console.log(map.next());
console.log(map.next());
}
{
let obj={
start:[1,3,2],
end:[7,9,8],
[Symbol.iterator](){
let self=this;
let index=0;
let arr=self.start.concat(self.end);
let len=arr.length;
return {
next(){
if(index<len){
return {
value:arr[index++],
done:false
}
}else{
return {
value:arr[index++],
done:true
}
}
}
}
}
}
for(let key of obj){
console.log(key);
}
}
{
let arr=['hello','world'];
for(let value of arr){
console.log('value',value);
}
}
for...of
*Generator
基本概念
解決異步編程 async和await就是它的語(yǔ)法糖
next函數(shù)的用法
yield*的語(yǔ)法
{
// genertaor基本定義
let tell=function* (){
yield 'a';
yield 'b';
return 'c'
};
let k=tell();
console.log(k.next());
console.log(k.next());
console.log(k.next());
console.log(k.next());
}
{
let obj={};
obj[Symbol.iterator]=function* (){
yield 1;
yield 2;
yield 3;
}
for(let value of obj){
console.log('value',value);
}
}
{
let state=function* (){
while(1){
yield 'A';
yield 'B';
yield 'C';
}
}
let status=state();
console.log(status.next());
console.log(status.next());
console.log(status.next());
console.log(status.next());
console.log(status.next());
}
// {
// let state=async function (){
// while(1){
// await 'A';
// await 'B';
// await 'C';
// }
// }
// let status=state();
// console.log(status.next());
// console.log(status.next());
// console.log(status.next());
// console.log(status.next());
// console.log(status.next());
// }
*Decorator
基本概念
是一個(gè)函數(shù)用來修改類的行為
基本用法
{
let readonly=function(target,name,descriptor){
descriptor.writable=false;
return descriptor
};
class Test{
@readonly
time(){
return '2017-03-11'
}
}
let test=new Test();
// test.time=function(){
// console.log('reset time');
// };
console.log(test.time());
}
{
let typename=function(target,name,descriptor){
target.myname='hello';
}
@typename
class Test{
}
console.log('類修飾符',Test.myname);
// 第三方庫(kù)修飾器的js庫(kù):core-decorators; npm install core-decorators
}
*模塊化
基本概念
ES6的模塊化語(yǔ)法
// export let A=123;
//
// export function test(){
// console.log('test');
// }
//
// export class Hello{
// test(){
// console.log('class');
// }
// }
let A=123;
let test=function(){
console.log('test');
}
class Hello{
test(){
console.log('class');
}
}
export default {
A,
test,
Hello
}
//導(dǎo)入
import Lesson17 form './class/lesson17'
console.log(Lesson17.A)