主要會貼上代碼轿衔,這樣容易理解些
持續(xù)更新中...
1.let const
/**let目锭,const 塊作用域內(nèi)有效 {}內(nèi)代表一塊*/
/**ES6 use strict*/
function test() {
// for(let i=1;i<3;i++){
// console.log(i);
// }
// console.log(i);
/**let 申明變量是不能重復定義*/
// let a= 1;
// let a=2;
}
function last() {
/*const常量不能修改(數(shù)值) 對象可以,如const k={}
* 申明時必須賦值
* */
const PI=3.1415926;
const k={
a:1
}
k.b=3;
console.log(PI,k);
}
last();
2.解構(gòu)賦值
主要講解了數(shù)組解構(gòu)賦值和對象解構(gòu)賦值,其他的都可以在上面拓展
依然貼上代碼:
/**
* 數(shù)組解構(gòu)賦值
*/
{
let a,b,rest;
[a,b]=[1,2];
console.log(a,b);
}
{
let a,b,rest;
[a,b,...rest]=[1,2,3,4,5,6];
console.log(a,b,rest);
}
/******/
{
let a,b,c,rest;
[a,b,c=3]=[1,2];
console.log(a,b,c);
}
/*變量交換*/
{
let a=1;
let b=2;
[a,b]=[b,a];
console.log(a,b);
}
/***/
{
function f() {
return [11,22]
}
let a,b;
[a,b]=f();
console.log(a,b);
}
/*選擇性接收變量*/
{
function f() {
return [1,2,3,4,5]
}
let a,b,c;
[a,,,b]=f();
console.log(a,b);
}
{
function f() {
return [1,2,3,4,5]
}
let a,b,c;
[a,,...b]=f();
console.log(a,b);
}
/*非常有用這種*/
{
function f() {
return [1,2,3,4,5]
}
let a,b,c;
[a,...b]=f();
console.log(a,b);
}
/*
* 對象解構(gòu)賦值
* */
{
let a,b;
({a,b}={a:10,b:20})
console.log(a,b);
}
{
let o={p:42,q:true}
let {p,q}=o;
console.log(p,q);
}
{
let {a=10,b=5}={a:3};
console.log(a,b);
}
{
let metaData={
title:'abc',
test:[{
title:'test',
desc:'des'
}]
}
let {title:esTitle,test:[{title:cnTitle}]}=metaData;
console.log(esTitle,cnTitle);
}
3.正則拓展
新增了2個修飾符 y和u枯跑,下面給出代碼:
{
let regex=new RegExp('xyz','i');
let regex2=new RegExp(/xyz/i);
console.log(regex.test('xyz123'),regex2.test('xyz123'));
let regex3=new RegExp(/xyz/ig,'i');
console.log(regex3.flags);
}
{
let s='bbb_bb_b';
let al=/b+/g;
let a2=/b+/y;
console.log(al.exec(s),a2.exec(s));
console.log(al.exec(s),a2.exec(s));
/*sticky是check 正則中是否帶有y修飾符*/
console.log(al.sticky,a2.sticky);
}
/*u修飾符
* 處理大于2個字節(jié)的 加u
* .并不是能匹配所有字符(必須是小于2個字節(jié)的字符)
* */
{
console.log('u-1',/^\uD83D/.test('\uD83D\uDc2A'));
console.log('u-2',/^\uD83D/u.test('\uD83D\uDc2A'));
console.log(/\u{61}/.test('a'));
console.log(/\u{61}/u.test('a'));
console.log(`\u{20BB7}`);
let s='';
console.log('u-1',/^.$/.test(s));
console.log('u-2',/^.$/u.test(s));
console.log('test',/{2}/.test(''));
console.log('test',/{2}/u.test(''));
}
4.字符串拓展(上)
Unicode編碼的一些問題肄方,貼上代碼,應該去敲一遍就可以理解
這里提醒滑绒,需要npm install babel-polyfill;得安裝這么個補丁包才行
{
console.log('a',`\u0061`);
console.log('s',`\u20BB7`);
console.log('s',`\u{20BB7}`);
}
{
let s='??';
/*es5中*/
console.log('length',s.length);
console.log('0',s.charAt(0));
console.log('1',s.charAt(1));
console.log('at0',s.charCodeAt(0));
console.log('at1',s.charCodeAt(1));
/*es6*/
let s1='??a';
console.log('length',s1.length);
console.log('code0',s1.codePointAt(0));
console.log('code0',s1.codePointAt(0).toString(16));
console.log('code1',s1.codePointAt(1));
console.log('code1',s1.codePointAt(2));
}
{
console.log(String.fromCharCode("0x20bb7"));
console.log(String.fromCodePoint("0x20bb7"));
}
{
let str='\u{20bb7}abc';
for(let i=0;i<str.length;i++){
console.log('es5',str[i]);
}
for(let code of str){
console.log('es6',code);
}
}
5.字符串拓展(下)
主要講解了一些日常中實用方便的方法,老規(guī)矩貼上代碼:
/**實用方法**/
/**
* 字符串中是不是包含某個字符
*/
{
let str="string";
console.log("includes",str.includes("a"));
console.log('start',str.startsWith('str'));
console.log('end',str.endsWith('g'));
}
/*字符串的復制*/
{
let str="abc";
console.log(str.repeat(4));
}
//模板字符串
{
let name="list";
let info="hello world";
let m=`i am ${name},${info}`;
console.log(m);
}
//es7草案 加了補丁包也可以在es6中使用
//補白的作用
{
//向前補
console.log('1'.padStart(4,'0'));
//向后補
console.log('1'.padEnd(4,'0'));
}
//標簽模板
{
let user={
name:'list',
info:'hello world'
};
console.log(abc`i am ${user.name},${user.info}`);
function abc(s,v1,v2) {
console.log("--s:",s,"v1:",v1,"v2:",v2);
return s+v1+v2;
}
}
//String.raw 使用頻率不是太高
{
console.log(String.raw`Hi\n${1+2}`);
console.log(`Hi\n${1+2}`);
}
6.數(shù)值拓展
跟數(shù)值有關的一些小方法骚露,僅僅碼出了常用的小部分蹬挤,更多請查閱
{
//二進制以0b開頭,b的大小寫都可以
console.log(0b111110111);
//八進制是0o開頭
console.log(0o767);
}
{
//Number.isFinite 是否無盡
console.log('5',Number.isFinite(5));
console.log('NaN',Number.isFinite(NaN));
console.log('1/0',Number.isFinite(1/0));
//Number.isNaN 是否為數(shù)字
console.log('NaN',Number.isNaN(NaN));
console.log('13',Number.isNaN(13));
}
{
//判斷是否為整數(shù)
console.log('25', Number.isInteger(25));
console.log('25.0', Number.isInteger(25.0));
console.log('1/3', Number.isInteger(1 / 3));
console.log('3/3', Number.isInteger(3 / 3));
console.log("abc", Number.isInteger('abc'));
}
{
console.log(Number.MAX_SAFE_INTEGER);
console.log(Number.MIN_SAFE_INTEGER);
//數(shù)是否安全
console.log("10",Number.isSafeInteger(10));
console.log("NaN",Number.isSafeInteger(NaN));
}
{
//取小數(shù)中的整數(shù)部分
console.log("4.1",Math.trunc(4.1));
}
{
//判斷正負0
console.log("-5",Math.sign(-5));
console.log("0",Math.sign(0));
console.log("5",Math.sign(5));
}
{
//立方根
console.log('9',Math.cbrt(9));
}
//es6中有三角函數(shù)方法+對數(shù)方法....
7.數(shù)組拓展
{
let arr=Array.of(3,4,7,9,11);
console.log(arr);
let empty=Array.of();
console.log(empty);
}
{
let p=document.querySelectorAll('p');
let pArr=Array.from(p);
pArr.forEach(function (item) {
console.log(item.textContent);
});
console.log(Array.from([1,3,5],function (item) {
return item*2;
}))
}
//填充數(shù)組
{
console.log('fill-7',[1,'a',undefined].fill(7));
console.log('fill,pos',['a','b','c','d','e'].fill(7,1,5));
}
{
for(let index of ['1','c','ks'].keys()){
console.log('keys',index);
}
//需要import 'babel-polyfill';
// for(let value of ['1','c','ks'].values()){
// console.log('values',value);
// }
for(let [index,value] of ['1','c','ks'].entries()){
console.log('values',index,value);
}
}
{
/**
* 它接受三個參數(shù)缚窿。
target (必需):從該位置開始替換數(shù)據(jù)棘幸。
start (可選):從該位置開始讀取數(shù)據(jù),默認為 0 倦零。如果為負值误续,表示倒數(shù)。
end (可選):到該位置前停止讀取數(shù)據(jù)扫茅,默認等于數(shù)組長度蹋嵌。如果為負值,表示倒數(shù)葫隙。
這三個參數(shù)都應該是數(shù)值栽烂,如果不是,會自動轉(zhuǎn)為數(shù)值恋脚。
*/
console.log([1,2,3,4,5].copyWithin(0,1,4));
}
{
/**查找*/
console.log([1,2,3,4,5,6].find(function (item) {
return item>3;
}));
console.log([1,2,3,4,5,6].findIndex(function (item) {
return item>3;
}))
}
{
console.log('number',[1,2,NaN].includes(NaN));
}
8.函數(shù)拓展
箭頭函數(shù)腺办,尾調(diào)用...
{
//參數(shù)可以設置默認值
//默認值的后面 必須也是默認值
//functon test(x,y='123',c) 就是錯誤的,必須得是c='1'
function test(x,y = 'word') {
console.log('默認值',x,y);
}
test('hello');
test('hello','kill');
}
{
let x='test';
function test2(x,y=x) {
console.log('作用域',x,y);
}
test2('kill');
//輸出 kill kill
}
{
function test3(...arg) {
for(let v of arg){
console.log('rest',v);
}
}
test3(1,2,3,4,'a');
//輸出 rest 1 rest 2 rest 3 rest 4 rest 5
//把輸入的參數(shù)轉(zhuǎn)成了數(shù)組
}
{
//擴展運算符
console.log(...[1,2,4]);
//輸出 1 2 4 把數(shù)組拆成離散的值
console.log('a',...[1,2,4]);
//輸出 a 1 2 4
}
//箭頭函數(shù)
{
//v 參數(shù) v*2返回值
//函數(shù)名 函數(shù)參數(shù) 函數(shù)返回值糟描,如果沒有參數(shù)就用() 表示
let arrow=v=>v*2;
console.log(arrow(3));
//輸出 6
let arrow2 = ()=>5;
console.log(arrow2());
//輸出 5
//箭頭函數(shù)的this指向
//箭頭函數(shù)中的this,指向與一般function定義的函數(shù)不同船响,比較容易繞暈躬拢,箭頭函數(shù)this的定義:箭頭函數(shù)中的this是在定義函數(shù)的時候綁定,而不是在執(zhí)行函數(shù)的時候綁定见间。
}
/**尾調(diào)用就是看 函數(shù)的最后一句話是不是一個函數(shù)
* 提升性能
* */
{
function tail(x) {
console.log('tail',x);
}
function fx(x) {
return tail(x);
}
fx(123);
//輸出 tail 123
}
9.對象拓展
{
//簡潔表示法
let o=1;
let k=2;
let es5={
o:o,
k:k
};
let es6={
o,k
}
console.log(es5);
console.log(es6);
let es5_method={
hello:function () {
console.log('hello');
}
}
let es6_method={
hello(){
console.log('hello');
}
}
es5_method.hello();
es6_method.hello();
}
{
//屬性表達式
let a='b';
let es5_obj={
a:'c',
b:'b'
};
let es6_obj={
[a]:'c'
}
console.log(es5_obj,es6_obj);
}
{
//新增api
//is 類似于===
console.log('字符串',Object.is('abc','an=bc'));
console.log('數(shù)組',Object.is([],[]),[1]===[1]);
console.log('拷貝',Object.assign({a:'a'},{b:'b',c:'c'},{z:'z'}));
let test={k:123,o:456};
for (let [key,value] of Object.entries(test)){
console.log([key,value]);
}
}
{
//拓展運算符
// let {a,b,...c}={a:'test',b:'kill',c:'ddd',d:'ccc'};
}
10.Symbol的用法
{
//聲明
let a1=Symbol();
let a2=Symbol();
console.log(a1===a2);
let a3=Symbol.for('a3');
let a4=Symbol.for('a3');
console.log(a3===a4);
}
{
let a1=Symbol.for('abc');
let obj={
[a1]:'123',
'abc':345,
'c':456
}
console.log(obj);
for(let [key,value] of Object.entries(obj)){
console.log(key,value);
}
Object.getOwnPropertySymbols(obj).forEach(function (item) {
console.log(obj[item]);
})
Reflect.ownKeys(obj).forEach(function (item) {
console.log(item,obj[item]);
})
}
11.set map數(shù)據(jù)結(jié)構(gòu)
簡單介紹了Set WeakSet Map WeakMap
{
let list=new Set();
list.add(5);
list.add(7);
console.log('size',list.size);
}
{
let arr=[1,2,3,4,5];
let list=new Set(arr);
console.log(list.size);
}
//去重
//數(shù)據(jù)類型得一致
{
let list=new Set();
list.add(1);
list.add(2);
list.delete(2);
list.add(1);
console.log(list);
let arr=[1,2,3,1,2];
let list2=new Set(arr);
console.log(list2);
}
{
let arr=['add','delete','clear','has'];
let list=new Set(arr);
console.log(list.has('add'));
list.delete('delete');
console.log(list);
list.clear();
console.log(list);
}
{
let arr=['add','delete','clear','has'];
let list=new Set(arr);
for(let key of list.keys()){
console.log('keys',key);
}
for(let value of list.values()){
console.log('value',value);
}
}
//weakset 只能是對象 弱引用 1.地址的引用 2.不會檢查地址是否被回收掉 3.沒有size,clear聊闯,不能遍歷
{
let weakList=new WeakSet();
let arg={
};
weakList.add(arg);;
console.log(weakList);
}
//map
{
let map=new Map();
let arr=['123'];
//add element
map.set(arr,456);
console.log(map,map.get(arr));
}
{
let map=new Map([['a',123],['b',456]]);
console.log(map);
console.log(map.size);
console.log(map.delete('a'),map);
console.log(map.clear(),map);
}
//weakmap 只能是對象 弱引用 1.地址的引用 2.不會檢查地址是否被回收掉 3.沒有size,clear,不能遍歷
{
let weakMap=new WeakMap();
let o={};
weakMap.set(o,123);
console.log(weakMap.get(o));
}
12.map-set與數(shù)組和對象的比較
將map set與數(shù)組和object都進行了增刪改查的比較
{
let list=new Set();
list.add(5);
list.add(7);
console.log('size',list.size);
}
{
let arr=[1,2,3,4,5];
let list=new Set(arr);
console.log(list.size);
}
//去重
//數(shù)據(jù)類型得一致
{
let list=new Set();
list.add(1);
list.add(2);
list.delete(2);
list.add(1);
console.log(list);
let arr=[1,2,3,1,2];
let list2=new Set(arr);
console.log(list2);
}
{
let arr=['add','delete','clear','has'];
let list=new Set(arr);
console.log(list.has('add'));
list.delete('delete');
console.log(list);
list.clear();
console.log(list);
}
{
let arr=['add','delete','clear','has'];
let list=new Set(arr);
for(let key of list.keys()){
console.log('keys',key);
}
for(let value of list.values()){
console.log('value',value);
}
}
//weakset 只能是對象 弱引用 1.地址的引用 2.不會檢查地址是否被回收掉 3.沒有size,clear米诉,不能遍歷
{
let weakList=new WeakSet();
let arg={
};
weakList.add(arg);;
console.log(weakList);
}
//map
{
let map=new Map();
let arr=['123'];
//add element
map.set(arr,456);
console.log(map,map.get(arr));
}
{
let map=new Map([['a',123],['b',456]]);
console.log(map);
console.log(map.size);
console.log(map.delete('a'),map);
console.log(map.clear(),map);
}
//weakmap 只能是對象 弱引用 1.地址的引用 2.不會檢查地址是否被回收掉 3.沒有size,clear馅袁,不能遍歷
{
let weakMap=new WeakMap();
let o={};
weakMap.set(o,123);
console.log(weakMap.get(o));
}
{
//數(shù)據(jù)結(jié)構(gòu)橫向?qū)Ρ龋鰟h改查
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.log(array);
//刪
map.delete('t');
let index=array.findIndex(item=>item.t);
array.splice(index,1);
console.log(map,array);
}
{
//set array對比
let set=new Set();
let array=[];
//增
set.add({t:1});
array.push({t:1});
console.log(set,array);
//查
let set_exist=set.has({t:1});
let array_exist=array.find(item=>item.t);
console.log(set_exist,array_exist);
//改
set.forEach(item=>item.t?item.t=2:'');
array.forEach(item=>item.t?item.t=2:'');
console.log(set,array);
//刪
set.forEach(item=>item.t?set.delete(item):'');
let index=array.findIndex(item=>item.t);
array.splice(index,1);
console.log(set,array);
}
//與object對比
{
let item = {t: 1};
let map = new Map();
let set = new Set();
let obj = {};
//增
map.set('t', 1);
set.add(item);
obj['t'] = 1;
console.log(map, set, obj);
//查
console.log(map.has('t'));
console.log(set.has(item));
console.log('t' in obj);
//改
map.set('t', 2);
item.t = 2;//修改成本高
obj['t'] = 2;
console.log(map, item, obj);
//刪
map.delete('t');
set.delete(item);
delete obj['t'];
console.log(map, set, obj);
}
/**
* 優(yōu)先使用map
* set作為考慮唯一性,對數(shù)據(jù)要求比較高荒辕,保證每個數(shù)據(jù)的唯一性汗销,使用set
* 數(shù)組+object放棄
*/
13.Proxy和Reflect
//代理
{
let obj={
time:'2017-03-11',
name:'net',
_r:'123'
};
let monitor=new Proxy(obj,{
//攔截對象屬性的讀取
get(target,key){
return target[key].replace('2017','2018');
},
//攔截對象設置屬性
set(target,key,value){
if (key==='name'){
return target[key]=value;
}else{
return target[key];
}
},
//攔截key in object 操作
has(target,key){
if(key==='name'){
return target[key];
}else{
return false;
}
},
deleteProperty(target,key){
/**
* IndexOf()與LastIndexOf()的不同在于IndexOf()從字符串中第一個字符開始檢索犹褒,
* LastIndexOf()是從字符串的最后一個字符向前檢索。
* 返回值都是字符串中字符所在的下標弛针,如果沒有找到則返回-1
*/
if(key.indexOf('_')>-1){
delete target[key];
return true;
}else{
return target[key];
}
},
//攔截Object.key,Object.getOwnPropertySmbols,Object.getOwnPropertyNames
ownKeys(target){
return Object.keys(target).filter(item=>item!='time');
}
});
console.log('get',monitor.time);
monitor.time='2019';
monitor.name='zhangjing';
console.log(monitor.time);
console.log(monitor.name);
console.log('has','name'in monitor,'time'in monitor);
// delete monitor._r;
// console.log('delete',monitor);
console.log('ownKeys',Object.keys(monitor));
}
//reflect 同proxy
{
let obj={
time:'2017-03-11',
name:'net',
_r:'123'
};
console.log(Reflect.get(obj,'time'));
Reflect.set(obj,'name','zhangjing');
console.log(obj);
console.log(Reflect.has(obj,'name'));
}
{
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} 不存在`);
}
}
})
}
const personValidators={
name(val){
return typeof val==='string'
},
age(val){
return typeof val==='number' &&val>18;
}
}
class Person{
constructor(name,age){
this.name=name;
this.age=age;
return validator(this,personValidators);
}
}
const person=new Person('李磊',19);
console.log(person);
// person.name=29;
person.name='zhang jing';
person.age=39;
}
14.類與對象
{
//基本定義和生成實例
class Parent{
constructor(name='zhangjing'){
this.name=name;
}
}
let v_parent=new Parent('v');
console.log('構(gòu)造函數(shù)和實例:',v_parent);
}
{
//繼承
class Parent{
constructor(name='zhangjing'){
this.name=name;
}
}
class Child extends Parent{
}
console.log('繼承',new Child());
}
{
//繼承傳遞參數(shù)
class Parent{
constructor(name='zhangjing'){
this.name=name;
}
}
class Child extends Parent{
//super一定放在第一行
constructor(name='child'){
super(name);
this.type='child';
}
}
console.log('繼承',new Child());
}
{
//getter setter
class Parent{
constructor(name='zhangjing'){
this.name=name;
}
get longName(){
return 'mk'+this.name
}
set longName(value){
this.name=value;
}
}
let v=new Parent();
console.log('getter',v.longName);
v.longName='hello';
console.log('setter',v.longName);
}
{
//靜態(tài)方法,static通過類去調(diào)用叠骑,而不是通過類的實例調(diào)用
class Parent {
constructor(name = 'zhangjing') {
this.name = name;
}
static tell(){
console.log('tell');
}
}
Parent.tell();
}
{
//靜態(tài)屬性
class Parent {
constructor(name = 'zhangjing') {
this.name = name;
}
static tell(){
console.log('tell');
}
}
Parent.type='test';
console.log('靜態(tài)屬性',Parent.type);
}
15.promise
主要講解了promise的原理,以及promise.all和promise.race的用法
//promise 解決異步操作
// {
// //es5 寫法
// 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');
// })
// }
// {
// 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');
// })
// }
// {
// let ajax=function (num) {
// console.log('執(zhí)行4');
// return new Promise(function (resolve,reject) {
// if(num>5){
// resolve();
// }else{
// throw new Error('出錯了!');
// }
// })
// }
//
// ajax(3).then(function () {
// console.log('log',6);
// }).catch(function (err) {
// console.log('catch',err);
// })
// }
// {
// //所有圖片加載完再添加到頁面
// function loadImg(src) {
// return new Promise((resolve,reject)=>{
// let img=document.createElement('img');
// img.src=src;
// img.onload=function () {
// resolve(img);
// }
// img.onerror=function (err) {
// reject(err);
// }
// })
// }
//
// function showImgs(imgs) {
// imgs.forEach(function (img) {
// document.body.appendChild(img);
// })
// }
//
// //把多個promise實例當做一個1個promise實例
// Promise.all([
// loadImg('http://i4.buimg.com/567571/df1ef0720bea6832.png'),
// loadImg('http://i4.buimg.com/567571/2b07ee25b08930ba.png'),
// loadImg('http://i2.muimg.com/567571/5eb8190d6b2a1c9c.png'),
// ]).then(showImgs);
// }
{
//先到先顯示
function loadImg(src) {
return new Promise((resolve,reject)=>{
let img=document.createElement('img');
img.src=src;
img.onload=function () {
resolve(img);
}
img.onerror=function (err) {
reject(err);
}
})
}
function showImgs(img) {
let p=document.createElement('p');
p.appendChild(img);
document.body.appendChild(p);
}
Promise.race([
loadImg('http://i4.buimg.com/567571/df1ef0720bea6832.png'),
loadImg('http://i4.buimg.com/567571/2b07ee25b08930ba.png'),
loadImg('http://i2.muimg.com/567571/5eb8190d6b2a1c9c.png'),
]).then(showImgs);
}
16.Iterator 和 for of
{
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);
}
}
3.17 Generator
Generator基本定義削茁,以及2個工作學習中常用到2個方法宙枷,長輪詢和類似抽獎的一個次數(shù)記錄
個人感覺generator跟async差不多,yeild跟await差不多茧跋。
Generator 函數(shù)是 ES6 提供的一種異步編程解決方案慰丛。
yield表達式是暫停執(zhí)行的標記,而next方法可以恢復執(zhí)行瘾杭。
記錄一個簡單的例子:
//genertaor基本定義
{
//定義generator
let tell=function* () {
yield 'a';
yield 'b';
return 'c';
};
let k=tell();
//這時候輸出為空诅病,因為程序調(diào)用tell函數(shù),然后遇到y(tǒng)ield就停止了粥烁。
//需要調(diào)用next()才能繼續(xù)執(zhí)行
console.log(k.next());
//next方法返回一個對象
// 它的value屬性就是當前yield表達式的值hello贤笆,done屬性的值false,表示遍歷還沒有結(jié)束讨阻。
//這句的輸出是{ value: 'a', done: false }
console.log(k.next());
//{ value: 'b', done: false }
console.log(k.next());
//{ value: 'c', done: true }
console.log(k.next());
//{ value: undefined, done: true }
}
{
let obj={};
obj[Symbol.iterator]=function* () {
yield 1;
yield 2;
yield 3;
}
for(let key of obj){
console.log(key);
}
}
{
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());
}
//generator 語法堂
// {
// 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());
// }
//抽獎
{
let draw=function (count) {
//具體抽獎邏輯
console.info((`剩余${count}次`))
}
let residue=function* (count) {
while (count>0){
count--;
yield draw(count);
}
}
let star=residue(5);
let btn=document.createElement('button');
btn.id='start';
btn.textContent='抽獎';
document.body.appendChild(btn);
document.getElementById('start').addEventListener('click',function () {
star.next();
},false)
}
{
//長輪詢
let ajax=function* () {
yield new Promise(function (resolve,reject) {
setTimeout(function () {
resolve({code:0});
},200);
})
}
let pull=function () {
let generator=ajax();
let step=generator.next();
step.value.then(function (d) {
if(d.code!=0){
setTimeout(function () {
console.log('wait');
pull()
},1000);
}else{
console.log(d);
}
})
}
pull();
}
18.Decorators
修飾器
{
//修飾器
let readonly=function (target,name,descriptor) {
descriptor.writable=true;
return descriptor
};
class Test{
@readonly
time(){
return '2017-9-04'
}
}
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);
}
//第三方修飾器的js庫:core-decorators
//npm install core-decorators
//案例
{
let log=(type)=>{
return function (target,name,descriptor) {
let src_method=descriptor.value;
descriptor.value=(...arg)=>{
src_method.apply(target,arg);
console.log(`log ${type}`);
}
}
}
class AD{
@log('show')
show(){
console.log('ad is show');
}
@log('click')
click(){
console.log('ad is click');
}
}
let ad=new AD();
ad.show();
ad.click();
}
19.模塊化
export:(2種方法芥永,個人比較喜歡最后一種)
//模塊引用 import
//模塊導出 export
// export let A=123;
//
// export function test() {
// console.log('test');
// }
//
// export class Hello{
// test(){
// console.log('class');
// }
// }
export let A=123;
export function test() {
console.log('test');
}
export class Hello{
test(){
console.log('class');
}
}
export default{
A,test,Hello
}
import:
// import {A,test,Hello} from './class/lesson17';
// import * as lesson17 from './class/lesson17';
//
// console.log(lesson17.A);
import Lesson17 from './class/lesson17';
console.log(Lesson17.A);
更新到這里,也就差不多暫時整理完了钝吮。接下來會有一個基于ES6技術棧寫的一個彩票系統(tǒng)網(wǎng)站埋涧,后面如果寫完了,會貼上GitHub