1、解构赋值
1.1、定义
什么是解构赋值?
ES6 允许按照一定模式,从数组和对象中提取值,对变量进行赋值,这被称为解构(Destructuring)。这种赋值语法极度简洁,同时还比传统的属性访问方法更为清晰。
其中包括:数组,对象的解构赋值,字符串的解构赋值,函数参数的解构赋值
1.2、数组解构
let test=[1,2,3];//es5let first = test[0];let second = test[1];let third = test[2];//es6let [first, , third] = test//fist//1//second//undefined
1.3、对象解构
let obj={ foo: "a", bar: "b" };//es5let foo= obj.foo;let bar= obj.bar;//es6let { foo, bar } = obj;//foo // "a"//bar // "b"
1.4、字符解构
const [a, b, c, d, e] = 'hello';console.log("d:", d);//llet { length } = "string";console.log("length:", length);//6
1.5、函数解构
//es5var arr = [1, 2];function test(a, b) {console.log("a:" + a);//1console.log("b:" + b);//2}test(arr[0], arr[1]);//es6var arr1 = [11, 22];function test1([a, b]) {console.log("a:" + a);//11console.log("b:" + b);//22}test1(arr1);var obj = { b: 33, a: 44 };function test2({ a, b }) {console.log("a:" + a);//33console.log("b:" + b);//44}test2(obj);//用法:let { floor, pow } = Math;console.log("a" + pow(3, 3));//9// 引入库const {toNumber,trim} = require('lodash');
2、运算符(…)
2.1、定义
(…)用于把一个数组转化为用逗号分隔的参数序列,它常用在不定参数个数时的函数调用,数组合并,替代es5的apply方法,与解构赋值结合,生成新数组等情形。
2.2、可变参数个数的函数调用
function add(...vals) {let sum = 0;for (let i = 0; i < vals.length; i++) {sum += vals[i];}return sum;}let test = [1, 2, 3, 4, 5];let sum = add(...test);//15
2.3、便捷的数组合并
let arr1 = [1,2];let arr2 = [5,6];let newArr = [20];//es5newArr = newArr.concat(arr1).concat(arr2); //[20,1,2,5,6]//es6newArr = [20,...arr1,...arr2]; //[20,1,2,5,6]
2.4、替代es5的apply方法
//ES5function f(x, y, z) {}var args = [0, 1, 2];f.apply(null, args);// ES6let args = [0, 1, 2];f(...args);//ES5Math.max.apply(null, [14, 3, 77])// ES6Math.max(...[14, 3, 77])//等同于Math.max(14, 3, 77);
2.5、与解构赋值结合,生成新数组
const [first, ...rest] = [1, 2, 3];//first // 1//rest // [2, 3]
3、箭头函数
3.1、定义
es6使用“箭头”(=>)定义函数。
箭头函数(arrow function),使用的频率非常的高,写法也是非常的简洁和清晰!
3.2、简化回调函数
[1,2,3].map(function (x) {return x * x;});// es6[1,2,3].map(x => x * x);const test = (head, ...tail) => [head, tail];test(1, 2, 3, 4, 5)// [1,[2,3,4,5]]//箭头函数取代Function.prototype.bind,不应再用self/_this/that绑定 this//es5const self = this;const boundMethod = function(...params) {return method.apply(self, params);}// es6const boundMethod = (...params) => method.apply(this, params);
4、箭头函数
4.1、定义
模板字符串(template string)是增强版的字符串,用反引号(`)标识。它可以当作普通字符串使用,也可以用来定义多行字符串,或者在字符串中嵌入变量,可多重嵌套。
4.2、简化回调函数
//es5let title = "hello world!"var tpl = '<div>' +'<span>' + title + '</span>' +'</div>';//es6let tpl2 = `<div><span>${title}</span></div>`;let tpl3 = `<div><span>${title+`<span>${title} 2016</span>`}</span></div>`;
5、export, import
5.1、定义
使用import取代require。
使用export取代module.exports。
5.2、简化回调函数
//es5const moduleA = require('moduleA');const func1 = moduleA.func1;const func2 = moduleA.func2;// es6import { func1, func2 } from 'moduleA'; //对象解构// commonJS的写法const commons = {SUCCESS: '请求成功',FAILED: '请求失败'}module.exports = commons;// ES6的写法const commons = {SUCCESS: '请求成功',FAILED: '请求失败'}export commons
6、for … of
6.1、定义
for…of循环,可以使用的范围包括数组、Set 和 Map 结构、某些类似数组的对象(比如arguments对象、DOM NodeList 对象)、Generator 对象,以及字符串。
6.2、遍历数组
const arr = ['red', 'green', 'blue'];for (let v of arr) {console.log(v); // red green blue}// 对比for-in和for-of:for (var k in arr) {console.log(k);} // 0 1 2var engines = new Set(["Gecko", "Webkit", "Webkit"]);for (var e of engines) {console.log(e);}// Gecko// Webkitvar es6 = new Map();es6.set("edition", 6);es6.set("standard", "ECMA-262");for (var [name, value] of es6) {console.log(name + ": " + value);}//edition: 6//standard: ECMA-262
6.3、遍历Set 和 Map 结构
let map = new Map().set('a', 1).set('b', 2);for (let pair of map) {console.log(pair);}// ['a', 1]// ['b', 2]for (let [key, value] of map) { //数组解构console.log(key + ' : ' + value);}//a : 1//b : 2
7、es6代码片段示例:
const moment = require('moment');const { pathConfig } = require('../config');const formatDate = (date) => {return moment(date).format('YYYY-MM-DD HH:mm');};const getPath = (picture) => {const pathParse = path.parse(picture.path);return `${pathConfig.PIC_DIR}${pathParse.dir}/${picture.name}_${pathParse.ext}`;};const assignPicture = (picture) => {const plain = picture.get({ plain: true});const path = getPath(plain);return assignIn(plain, {path: path,created_at: formatDate(picture.created_at),});};const getResult = (pictureRs) => {const assignedResultRows = pictureRs.rows.map(assignPicture);return {count: pictureRs.count,rows: assignedResultRows,};};
8、小结
以上是平时用得比较多的内容,这些语法、新增类型、模块调用等从代码量上、可读性上、操作上给项目带来了不少便利。
随着es6的普及,这些高级语言的特性让写js也越来越顺畅。
9、参考资料
1.ECMAScript 6 入门http://es6.ruanyifeng.com/
ES6 扩展运算符 三个点(…)
http://www.jianshu.com/p/86cbabeda999es6的常用语法和优越性https://juejin.im/post/5a08e5c55188252abc5dd96f#heading-2
ES6的一些常用特性
https://www.cnblogs.com/MuYunyun/p/6235325.html#_label6
