logo

Timeless

花开成景,花落成诗

ES6 常用新特性总结

ES6 常用新特性总结

六月 15, 2020 35 544 2 分钟

ES6, 全称 ECMAScript 6.0,2015.06 发版,主要是为了解决 ES5 的先天不足,增加了许多新特性。

ES6, 全称 ECMAScript 6.0,2015.06 发版,主要是为了解决 ES5 的先天不足,增加了许多新特性。

1、数组

1.1、数组求和

reduce方法本意就是用来记录循环的累积结果,用于数组求和是最合适不过了

const total = [1, 2, 3, 4].reduce((accumulator, current) => accumulator += current, 0); // 10

1.2、数组去重

一维数组:

使用SetSet是ES6新提供的数据结构,类似于数组,但是本身没有重复值。

const arr = [1, 2, 2, 3, 3, 3]
// 使用Array.from
Array.from(new Set(arr))
// 使用扩展运算符
[...new Set(arr)]

使用MapMap对象保存键值对,has方法返回一个布尔值,表示某个键是否在当前Map对象中。

function unique(arr) {
    const res = new Map();
    return arr.filter((a) => !res.has(a) && res.set(a, 1))
}

对象数组:

const arr = [{id:1, name: '张三'}, {id: 2, name: '李四'}, {id: 1, name: '王五'}]
const temp = {}
const result = arr.reduce((cur, next) => {
  if(!temp[next.id]) {
    temp[next.id] = true
    cur.push(next)
  }
  return cur
}, [])

1.3、数组扁平化

将二维数组转化为一维

const arr = [[0, 1], [2, 3], [4, 5]]
const newArr = arr.reduce((pre,cur)=>{
    return pre.concat(cur)
},[])
console.log(newArr); // [0, 1, 2, 3, 4, 5]

涉及到数组的扁平化处理,可以使用flat方法

const arr = [[0, 1], [2, 3], [4, 5]]
const result = arr.flat(Infinity);

其中使用Infinity作为flat的参数,使得无需知道被扁平化的数组的维度。

2、字符串

2.1、补全字符串

比如16进制补全前导零,es5实现

/**
 * 10进制转16进制字符串
 * @param {Number} dec 10进制
 * @param {Number} len 目标字符串长度,不足的补前导0
 * @returns {String}
 */
function decimal2Hex(dec, len){
  const hex = dec.toString(16).toUpperCase()
  return (Array(len).join(0) + hex).slice(-len);   // 16进制不及目标长度前导补0
}

es6 padStart()用于头部补全,padEnd()用于尾部补全

function decimal2Hex(dec, len) {
  const hex = dec.toString(16).toUpperCase()
  return hex.padStart(len, '0')
}

2.2、非空判断

在处理输入框相关业务时,往往会判断输入框未输入值的场景

if(value != null && value !== ''){
    //...
}

ES6空值合并运算符

if(value??'') {
  // ...
}

2.3、字符串拼接

const name = '张三';
const score = 59;
const result = `${name}的考试成绩${score > 60 ? '' : '不'}及格`;

恰饭区

广告位招租

评论

Power by Node.js + Nuxt.js,由 腾讯云 腾讯云提供服务, 已经稳稳地存活了 8年95天

Copyright © 2018 - 2026 Timeless. All rights reserved.桂ICP备18003656号-1公网安备桂公网安备45092102000147号