title: ES6-01
date: 2017-06-30 15:36:47
tags: ES6
---
前言:vue
指導了一些es6的用法,可是一直沒有系統的看關於es6的全部改變,因而此次看阮一峯的ES6標準入門,記錄下來方便本身查詢jquery
.babelrcgit
{ "presets":[ "es2015", "stage-2" ], "plugins":[] }
packagees6
{ "name": "es6Demo", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "build": "babel src -d lib" }, "repository": { "type": "git", "url": "git+https://github.com/zeroHu/es6Demo.git" }, "keywords": [], "author": "", "license": "ISC", "bugs": { "url": "https://github.com/zeroHu/es6Demo/issues" }, "homepage": "https://github.com/zeroHu/es6Demo#readme", "devDependencies": { "babel-cli": "^6.24.1", "babel-preset-es2015": "^6.24.1", "babel-preset-stage-2": "^6.24.1" } }
title: ES6-02
date: 2017-06-30 16:51:25
tags: ES6
---github
1.let命令所在的代碼塊內有效,
2.let不容許聲明重複的變量,
3.let不會存在變量提高(若是在聲明前使用會報錯)web
{ let a = 0; var b = 1; } a //ReferenceErr b //1
1.const是聲明一個只讀的常量,也是代碼塊內ajax
if(true){ const MAX = 5; } MAX // Uncaught ReferenceError
title: ES6-03
date: 2017-06-30 17:26:10
tags: ES6
---json
es5 聲明變量的方式 var a = 1; var b = 2; var c = 3; var sendA = [], sendB = [], sendC = []; es6 聲明變量的方式 let [a,b,c] = [1,2,3]; let [sendA,sendB,sendC] = [[],[],[]]; //more example let [head, ...tail] = [1, 2, 3, 4]; head // 1 tail // [2, 3, 4]
這種寫法爲模式匹配,只要等號兩邊相等就能夠匹配,解構賦值不只適用於var命令 , 解構不只能夠用於數組,還能夠用於對象。,也適用於let和const命令。api
let [x,y,z] = new Set(["a","b","c"]) //x : a
let {a,b} = {foo:"aa",bar:bb} let { a = {}, b= {} } = {};
const [a,b,c,d,e] = 'hello'; //a 'h' ... //e 'o'
function add([x+y]){ return x+y } add([1,2])//3
title: ES6-04
date: 2017-07-03 17:07:43
tags: ES6
---數組
- includes():返回布爾值,表示是否找到了參數字符串。
- startsWith():返回布爾值,表示參數字符串是否在源字符串的頭部
- endsWith():返回布爾值,表示參數字符串是否在源字符串的尾部。
var s = 'Hello world!'; s.startsWith('Hello')// true s.endsWith('!') // true s.includes('o') // true
let newarr = 'x'.repeat(10); //'xxxxxxxxxx'
" ``` let str = 'history'; console.log(
this vue mode is ${str}`);//this vue mode is historyconst tmpl = addrs => ` <table> ${addrs.map(addr => ` <tr><td>${addr.first}</td></tr> <tr><td>${addr.last}</td></tr> `).join('')} </table> `; const data = [ { first: '<Jane>', last: 'Bond' }, { first: 'Lars', last: '<Croft>' }, ]; console.log(tmpl(data));
#### 模板編譯實例
let str = 'history';
console.log(this vue mode is ${str}
);
const tmpl = addrs => <table> ${addrs.map(addr =>
${addr.first} ${addr.last}
).join('')} </table>
;
const data = [
{ first: '
console.log(tmpl(data));
#### 標籤模板 > 是用來防止用戶輸入惡意代碼
alert`hello` //等價於 alert(hello) var a = 5; var b = 10; tag`Hello ${ a + b } world ${ a * b }`; // 等同於 tag(['Hello ', ' world ', ''], 15, 50);
--- title: ES6-05 date: 2017-07-04 11:55:08 tags: ES6 --- ### 數組的拓展 #### Array.from() > Array是將兩類對象轉爲真正的數組,相似數組的對象(array-like object)和可遍歷(iterable)的對象(包括ES6新增的數據結構Set和 Map)
let arraylike = { 'time':'12', 'year':'13', 'name':'zero' }; let array = Array.from(arraylike); console.log(array)
#### 拓展運算符(...)也能夠將某些數據結構轉爲數組
// arguments對象
function foo() {
var args = [...arguments];
}
// NodeList對象
[...document.querySelectorAll('div')]
#### 數組實例的includes()
[1,2,34].includes(1);//true
['a','b','cd'].includes('f');//false
#### 數組的map filter --- title: ES6-06 date: 2017-07-04 18:46:19 tags: ES6 --- ### 箭頭函數
var f = f => f
//等同於
var f = function(f){
return f;
}
> 去空,去重,排序函數
const needPartKong = (arr) => Array.from(new Set(arr));//去重 1
let needarr = [1,2,3,2,1];
console.log(needPartKong(needarr));//[ 1, 2, 3 ]
console.log(needarr);//[ 1, 2, 3, 2, 1 ]
arr = [...new Set(arr)] //去重 2
> 若是箭頭函數不須要參數或者須要多個參數的時候須要用()包含
var pagejson = {
init(){
//此處的this指向的並非 $('.divone') 而是始終指向pagejson
$('.divone').click(() => this.getData());
},
getData(){
console.log('get data is ...');
}
}
> 箭頭函數的this指向是不會隨綁定的對象而改變的而是定義的時候this的環境 --- title: ES6-07 date: 2017-07-06 14:38:18 tags: ES6 --- ### Object #### Object.keys()
var json = {foo:"1",baz:"2"}; Object.keys(json);//['foo','baz']
#### Object.values()
var json = {foo:"1",baz:"2"}; Object.values(json);//['1','2']
### Object.entries()
var json = {foo:"1",baz:"2"}; Object.entries(json);//[['foo','1'],['baz','2']]
--- title: ES6-08 date: 2017-07-06 21:51:39 tags: ES6 --- ### Generator函數 > Generator函數有多種理解角度。從語法上,首先能夠把它理解成,Generator函數是一個狀態機,封裝了多個內部狀態 --- title: ES6-promise date: 2017-07-10 19:14:47 tags: ES6 --- ### promise > 處理後一個ajax 依賴前一個ajax的結果的請求
var ajax = function(option){
return new Promise(function(resolve, reject){
$.ajax({
url: option.url,
type: option.type || 'get',
data: option.data || '',
success: function(data){
resolve(data);
},
error: function(error){
reject(error);
}
});
});
};
var p1 = ajax({
url: 'url1',
method:'post',
data:{
code:'xxx'
}
});
p1.then(function(resp1Data){
console.log(resp1Data);
return ajax({
url: 'url2'
});
})
.then(function(resp2Data){
console.log(resp2Data);
});
> 處理多個ajax之間的請求相互不影響,可是最後執行語句的狀況是要求全部ajax都已經執行完畢,返回結果的狀況
jquery 的 $.when就是利用promise實現
function getDataFun(){
var fun1 = $.ajax({url: "/equip_rank",type:'GET',dataType:'jsonp'}),
fun2 = $.ajax({url: "/score_rank",type:'GET',dataType:'jsonp'}),
fun3 = $.ajax({url: "/billionaire_rank",type:'GET',dataType:'jsonp'});
$.when(fun1,fun2,fun3).then(function(data1,data2,data3){
//成功回調,全部請求正確返回時調用
console.log(data1[0]);
console.log(data2);
console.log(data3);
},function(){
//失敗回調,任意一個請求失敗時返回
console.log('fail!!');
})
}
var ajax = function(options){
return new Promise(function(resolve,reject){
$.ajax({
url:options.url,
type:options.type || 'get',
data:options.data || {},
success(res){
resolve(res);
},
error(res){
reject(res);
}
})
})
}
var p1 = ajax({url:'xxxx',type:'post',data:{xxx:'fff'}}),
p2 = ajax({url:'xxxx',type:'post',data:{xxx:'fff'}}),
p3 = ajax({url:'xxxx',type:'post',data:{xxx:'fff'}});
Promise.all([p1,p2,p3]).then(function(results){
results.forEach(function(result){
console.log(result.statusCode);
});
}).catch(function(err){
console.log(err);
});
testPromise(){
var ajax = function(option){
return new Promise(function(resolve,reject){
$.ajax({
url:option.url,
type:option.type || 'get',
data:option.data || {},
success(data){
resolve(data);
},
error(data){
reject(data);
}
})
})
}
// 獲取用戶信息
var p1 = ajax({
url:'/api/website/user/info/',
type:'get'
});
// 微信簽名
var p2 = ajax({
url:'/api/website/signature/weixin/',
type:'post',
data:{
url:location.href,
type:'pay'
}
});
// 獲取商品信息
var p3 = ajax({
url:'/api/website/pay/product/info/',
type:'post',
data:{
products:'44bd8d05d4f44c629a493b1754da6dc0'
}
});
// 異步請求函數 Promise.all([p1,p2,p3]).then(function(results){ results.forEach(function(result){ console.log('all====>',JSON.stringify(result)); }); }).catch(function(err){ console.log(err); }); // 同步請求函數 p1.then(function(resp1) { console.log('resp1', JSON.stringify(resp1)); console.log(123); return p2; }).then(function(resp2) { console.log(234); console.log('resp2', JSON.stringify(resp2)) return p3; }).then(function(resp3) { console.log(345); console.log('resp3', JSON.stringify(resp3)) });
}
```