ES6实用特性

一、展开操作符 (...)

es6写法
let firstHalf = [  one ,  two ];
let secondHalf = [ three ,  four , ...firstHalf];

传统写法
let firstHalf = [  one ,  two ];
let secondHalf = [ three ,  four ];
for(var i=0, i <firstHalf.length; i++ ) {
  secondHalf.push(firstHalf[i]);
}

展开操作符也适用于合并对象的属性:
const hero = {
  name:  Xena - Warrior Princess ,
  realName:  Lucy Lawless
}
const heroWithSword = {
 ...hero,
 weapon:  sword
}
传统写法:不用展开操作符的话,需要遍历对象的属性:
let keys = Object.keys(hero);
let obj = {};

for(var i=0; i< keys.length; i++) {
   obj[keys[i]] = keys[props[i]];
}

二、模板字符串、字符串插值 (${a} )

传统写法
function fn(a,b){ 
      return a + "说:今天星期一!"+ b + "放学来我家玩!"
}
fn("小明","小红")
使用模板字符串
function fn(a,b){ 
      return  `${a}说:今天星期一!${b}放学一起走!`
}
fn("Lucy","小红")

三、解构赋值

对象解构赋值
const data = {
      person: {
	name: "lili",
	age: 12,
      },
      address: "河北",
}
//结构赋值--避免逐个取
const { person: { name, age },address,} = data   //name, age, address
数组解构赋值
const arr = [1, 2, 3, 4, 5, 6]
const [a, , c, ...remaining] = arr
console.log(a, c, remaining)    //remaining是代表剩余参数,也是es6新增的

四、数组方法

ES6 引入了许多有用的数组方法,例如:
find(),查找列表中的成员,返回 null 表示没找到
findIndex(),查找列表成员的索引
some(),如果有一个元素满足条件,则表达式返回true
includes,列表是否包含某项

const obj = [{ id: 1, checked: true }, { id: 2 },9]
const m = obj.find((item) => { item.id === 2})// { id: 2 }
const n = obj.findIndex((item) => item.id == 1)// 1
const p = arr.some(item => item.checked) // true
numberArray.includes(9) // true

五、模块

// math.js

export function add(a,b) { return a + b; }
export function sub(a,b) { return a - b; }

export default mult(a,b) => a * b;

// main.js
import mult, { add, sub } from  ./math ;

mult(2, 4) // 8
add(1,1)   // 2
sub(1,2)   // -1
原文地址:https://www.cnblogs.com/maizilili/p/13220193.html