es6的一些技巧总结(1)

1、对象解构

(1)删除不需要的属性

let {a,b,...c} = {a:1,b:2,ele1:3,ele2:4,ele3:5}
console.log(c)//{ele1:3,ele2:4,ele3:5}

(2)获取需要的属性

let a = {
  a1:1,
  b:{
    b1:1,
    b2:2,
    b3:3
  }
}
const getAttr({a1,b:{b1}})=>{
  console.log(`a1${a1} b1:${b1}}`)
}
(3)合并对象
let a = {a1:1,a2:2,a3:3}
let b = {b1:1,b2:2,b3:3}
let merger = {...a,...b}

2、Set

(1)数组去重

let arr = [1,1,2,2,3,3]
let afterArr = [...newSet(arr)]

(2)并集(union),交集(intersect),差集(difference)

let a = new Set([1,2,3])
let b = new Set([4,3,2])

//并集
let union = new Set([...a,...b])
//交集
let intersect = new Set([...a].filter(x=>b.has(x)))
//差集
let intersect = new Set([...a].filter(x=>!b.has(x)))

3、数组

(1)数值交换

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

(2)return 多个结果

async function getBack(){
  return await Promise.all([
   fetch('/get1')
   fetch('/get2')
  ])
}
const [get1,get2] = getBack()

(3)代替es5的apply

function f(x,y,z){
  //...
}
const arr = [1,2,3]
//es5
f.apply(null,arr)
//es6
f([...arr])

(4)数组的合并

let arr1 = [1,2,3]
let arr2 = [4,5,6]
let mergeArr = [...arr1,...arr2]
let mergeArr = arr1.push[...arr2]

(5)字符串转数组

[...'hello']
//['h','e','l','l','o']

(6)Array.from()类数组转化为数组(DOM集合)

let p = document.querySelectorAll('p');
Array.from(p).forEach(p=>{
  //...
})

Array.from([1,2,3],x=>x*x)//可接受处理函数

(7)Array.of()将一组值转化为数组

Array.of(1,2,3)==[1,2,3]
Array.of(1,2,3).length = 3

(8)entries(),keys(),values()

for(let index of[1,2].keys()){
  console.log(index)
}
//0,1
for(let value of[1,2].values()){
  console.log(value)
}
//1,2
for(let [index,value] of[1,2].entries()){
  console.log(index,value)
}
//0,1
//1,2

4、函数

(1)指定某一个函数参数默认值不能省略

function throwIfMissing(){
 throw new Error('Missing parameter')
}
function f(a=throwIfMissing()){
 return a
}
f()//Error:Missing Paramter

5、标签模板

function SaferHTML(template){
  let s = template[0]
  for(let i =1;i<template,length;i++){
   let arg = templatep[i]
    s+=arg.replace(/&/g,"&")
          .replace(/>/g,"<")
          .replace(/</g,">")
    s+=template[i]
  }
return s
}

let messgae = SaferHTML`<p>${send}</p>`




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值