10/18 奇妙之旅
推荐:《精通Node.js开发》 《Angular.js视频详解》
微信号 forjs_org
今天是周六,上午温习一下es6的用法。
destructuring
let [,x,y] = [1,3,2];
let {a,b,c} = {a:3,b:6,c:9};
let {a:a1,b,c:{h:h}} = {a:3,b:6, c:{h:9} }; // {a1,b,h}
function test ({a,b,c}){
return a;
}
test({a:12,b:3:c:5}) // 12
Defualt parameter values
function test(url="forjs.org" , {name = "leo" , age}){
// ...
}
Rest parameters
function test(...nums){
nums.forEach(function(n){
...
})
}
Spread Operator
function test(x,y,z){
return x + y+z;
}
var arr = [1,2,3];
test(...arr) // 6
Template Literals
var sub = "book";
let url = `http://forjs.org/${sub}`
function test(str,...values){
}
let x=1,y=3;
var result = test `${x} + ${y} is ${x+y}`
// str = [""," + ", " is ", ""]
// values = [1,3,4]
Arrow Function
let add = (x,y) => x + y;
//or
let add = (x,y) => {
return x + y;
}
let sum = 0,numbers = [1,2,3,4];
numbers.forEach(n => sum += n);
// 如果两个参数可以 (n,m) => sum + n +m ;
Iterables and Iterators
next()
{value:xxx , done:true/false}
var numbers = [1,2,23,3,2];
// create a iterator
let iterator = numbers.values();
let next = iterator.next(); // {value :1 , done : false}
for of
for of 使用的是
iterator
技术支持!, 必须实现 iterator 方法,得到 iterator对象。
var numbers = [1,2,23,3,2];
for(let n of numbers){
console.log(n);
}
// 1,2,23,3,2
不明白的写法
class User{ Symbol.iterator{ // why
} }
Generators
let numbers = function *(){
yield 1;
yeild 2;
}
var iterator = numbers();
// ... ...
特殊写法
clsss User{
*iterator(){ // generator 写法
yield 12;
}
}
Comprehensions 解析
var numbers = [for(n of [1,2,3]) n * n];
// [1,4,9]
var numbers = (for(n of [1,2,3]) n * n); // ?
yield [if(true) 12 ] // yield 12
yield* [12,14] // yield 12 ; yield 14;
Arrays
var match = [1,2,3,10].find(item => item > 8);
var arr = ...
arr.findInex(item => item > 3)
arr.fill("a")
arr.fill("a",2,3)
// [1,2,3,4]
arr.copyWithin(2,0,1); // 1,2,1,4
var arr = new Array(1,2,3); // [1,2,3]
var ofAry = Array.of(3) // [3]
var arrayLink = document.querySelectorAll("div");
var fromArray = Array.from(arrayLink); // -> Array type.
var entries = arr.entries();
var r = entries.next().value; // [0,"Joe"]
解构
var [x,,y] = [12,11,15];
console.log(x,y);
拓展参数
let test(p1,p2,p3) => console.log(`Hello ${p1} ${p2} ${p3}`);
var ps = [11,22,33];
test(...ps); // 原始使用 ps.apply(null,ps);