ES6 简写

对象属性简写

const obj = { x:x, y:y };

简写为

const obj = { x, y };

对象方法的简写

const obj = {
	fun: function () {}
}

简写为

const obj = {
	fun () {}
}

箭头函数简写

无返回值简写

list.forEach(function(item) {
  console.log(item);
});

简写为

list.forEach(item => { console.log(item) });

有返回值简写

function calcCircumference(diameter) {
  return Math.PI * diameter
}

简写为

calcCircumference = diameter => Math.PI * diameter;

无参数

setTimeout(function() {
  console.log('Loaded')
}, 2000);

简写为

setTimeout(() => console.log('Loaded'), 2000);

参数默认值

function volume(l, w, h) {
  if (w === undefined)
    w = 3;
  if (h === undefined)
    h = 4;
  return l * w * h;
}

简写为

volume = (l, w = 3, h = 4 ) => (l * w * h);

模板字符串

const welcome = 'You have logged in as ' + first + ' ' + last + '.'

简写为

const welcome = `You have logged in as ${first} ${last}`;

解构赋值

路径解析

const observable = require('mobx/observable');
const action = require('mobx/action');
const runInAction = require('mobx/runInAction');

简写为

import { observable, action, runInAction } from 'mobx';

对象解析

const props = {
	a: 'a',
    b: 'b'
}
const a = props.a;
const b = props.b;

简写为

const { a, b } = this.props;

数组解析

const arr = [2, 5, 8]
const a = arr[0]
const b = arr[1]
const c = arr[2]

简写为

const arr = [2, 5, 8]
[a, b, c] = arr

元素交换

[varA, varB] = [varB, varA];
// [x, y] = [y, x]

let [a, b] = [2, 5]
[b, a] = [a, b]

展开运算符

// 拼接数组
const odd = [1, 3, 5];
const nums = [2 ,4 , 6].concat(odd);
// 克隆数组
const arr = [1, 2, 3, 4];
const arr2 = arr.slice()

简写为

const odd = [1, 3, 5 ];
const nums = [2, ...odd, 4 , 6];

MIT Licensed | Copyright © 2018-present 滇ICP备16006294号

Design by Quanzaiyu | Power by VuePress