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)) });
}
```