Timeless
花开成景,花落成诗
ES6, 全称 ECMAScript 6.0,2015.06 发版,主要是为了解决 ES5 的先天不足,增加了许多新特性。
ES6, 全称 ECMAScript 6.0,2015.06 发版,主要是为了解决 ES5 的先天不足,增加了许多新特性。
reduce方法本意就是用来记录循环的累积结果,用于数组求和是最合适不过了
const total = [1, 2, 3, 4].reduce((accumulator, current) => accumulator += current, 0); // 10
一维数组:
使用Set,Set是ES6新提供的数据结构,类似于数组,但是本身没有重复值。
const arr = [1, 2, 2, 3, 3, 3]
// 使用Array.from
Array.from(new Set(arr))
// 使用扩展运算符
[...new Set(arr)]
使用Map,Map对象保存键值对,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
}, [])
将二维数组转化为一维
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的参数,使得无需知道被扁平化的数组的维度。
比如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')
}
在处理输入框相关业务时,往往会判断输入框未输入值的场景
if(value != null && value !== ''){
//...
}
ES6空值合并运算符
if(value??'') {
// ...
}
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号
评论