ES6 实用方法(持续更新)

71 阅读2分钟

1、合并一维数组且去重

const a = [1,2,3];
const b = [1,2,4];
const c = [...new Set([...a, ...b])] // [1,2,3,4]
 

2、列表搜索精准定位

const a = [1,2,3,4];
const result = a.find(item => item === 3);

3、扁平化合并数组-flat(flat不支持IE)

const deps = {
    '采购部':[1,2,3],
    '人事部':[5,8,12],
    '行政部':[5,14,79],
    '运输部':[3,64,105],
}
let member = Object.values(deps).flat(Infinity); // Infinity使用者无需知道数组的维度

4、值的非空判断

if(value !== null && value !== undefined && value !== ''){}
等于
if((value ?? '') !== '' ){}

5、for...of循环

一个数据结构只要部署了 Symbol.interator ,就可以用 for...of 进行循环遍历其成员

// 创建一个遍历器
function readLinesSync(file) {
    return {
        [Symbol.iterator]() {
            return {
                next() {
                    // 由 Generator 规格决定,必须return一个对象
                    return { done: false };
                },
                return() {
                    file.close();
                    return { done: true };
                }
            };
        },
    };
}
 
for (let line of readLinesSync(fileName)) {
    console.log(line);
    break; // 或 throw new Error 强制跳出
}

6、Generator 函数

下文gen是一个 Generator 函数,调用它会生成一个遍历器对象g。它的Symbol.iterator属性,也是一个遍历器对象生成函数,执行后返回它自己。

function* gen(){
    // some code
}
var g = gen();
g[Symbol.interator]() === g;
// true

Generator使用场景

  • yield暂停执行,替换异步操作
function showLoadingScreen() {
    console.log('showLoadingScreen')
}
 
function loadUIDataAsynchronously() {
    console.log('loadUIDataAsynchronously')
}
 
function hideLoadingScreen() {
    console.log('hideLoadingScreen')
}
 
function* loadUI() {
  showLoadingScreen();
  yield loadUIDataAsynchronously();
  hideLoadingScreen();
}
 
var loader = loadUI();
// 加载UI
loader.next()
setTimeout(()=>{
    // 卸载UI
    loader.next()
},3000)
 
// showLoadingScreen
// loadUIDataAsynchronously
// 107877
// hideLoadingScreen
  • 使用场景2,多个promise进程优化,且task需要是同步操作
Promise.resolve(step1)
  .then(step2)
  .then(step3)
  .then(step4)
  .then(function (value4) {
    // Do something with value4
  }, function (error) {
    // Handle any error from step1 through step4
  })
  .done();
 
 
// 优化
function* longRunningTask(value1) {
  try {
    var value2 = yield step1(value1);
    var value3 = yield step2(value2);
    var value4 = yield step3(value3);
    var value5 = yield step4(value4);
    // Do something with value4
  } catch (e) {
    // Handle any error from step1 through step4
  }
}
 
 
scheduler(longRunningTask(initialValue));
function scheduler(task) {
  var taskObj = task.next(task.value);
  // 如果Generator函数未结束,就继续调用
  if (!taskObj.done) {
    task.value = taskObj.value
    scheduler(task);
  }
}
  • 场景3 跟数组解构一起使用
const go = function*(){
  yield 1;
  yield 2;
  yield 3;
};
[...go()] // [1, 2, 3]

参考文档: [1]www.bookstack.cn/read/es6-3r…

[2]掘金上的一片文档,没记到地址