js优秀代码片段(持续更新)

方法

数组去重

// 第一种
let array = [1, 1, 2, 3, 4, 4, 5];
let res = [...new Set(array)];
// 第二种
let array = [1, 1, 2, 3, 4, 4, 5];
let res = Array.from(new Set(array));
// 第三种
let array = [1, 1, 2, 3, 4, 4, 5];
let res = array.filter((item, index) => array.indexOf(item) === index);

两个数组对象对比,去除重复的对象

// array1中去除在array2重复的
let array1 = [
  { id: 1, name: "zhangsan" },
  { id: 2, name: "lisi" },
  { id: 3, name: "wangwu" },
];
let array2 = [
  { id: 1, name: "zhangsan" },
  { id: 3, name: "wangwu" },
];
let res = array1.filter((v) => !array2.some((vv) => v.id === vv.id));
// 打印后,res只有id是2的了

生成指定长度的数组

// 生成100个数组
let array = [...Array(100).keys()];

数组取交集

const a = [0, 1, 2, 3, 4, 5];
const b = [3, 4, 5, 6, 7, 8];
const duplicatedValues = [...new Set(a)].filter((item) => b.includes(item));
duplicatedValues; // [3, 4, 5]

数组取差集

const a = [0, 1, 2, 3, 4, 5];
const b = [3, 4, 5, 6, 7, 8];
const diffValues = [...new Set([...a, ...b])].filter(
  (item) => !b.includes(item) || !a.includes(item)
); // [0, 1, 2, 6, 7, 8]

数组 reduce

代替some和every
const scores = [
    { score: 45, subject: "chinese" },
    { score: 90, subject: "math" },
    { score: 60, subject: "english" }
];

// 代替some:至少一门合格
const isAtLeastOneQualified = scores.reduce((t, v) => t || v.score >= 60, false); // true

// 代替every:全部合格
const isAllQualified = scores.reduce((t, v) => t && v.score >= 60, true); // false

一维数组转树形结构(第一种)

let list = [
  { id: 1, name: "节点1", pid: 0 },
  { id: 11, name: "节点1-1", pid: 1 },
  { id: 111, name: "节点1-1-1", pid: 11 },
  { id: 12, name: "节点1-2", pid: 1 },
  { id: 121, name: "节点1-2-1", pid: 12 },
  { id: 2, name: "节点2", pid: 0 },
  { id: 3, name: "节点3", pid: 0 },
  { id: 31, name: "节点3-1", pid: 3 },
  { id: 32, name: "节点3-2", pid: 3 },
];
const listToTree = (list, pid) => {
  let res = [];
  list.forEach((v) => {
    if (v.pid == pid) {
      v.children = listToTree(list, v.id);
      res.push(v);
    }
  });
  return res;
};

// 输出包含children层级关系的树形结构
console.log(listToTree(list, 0));

一维数组转树形结构(第二种)

let list = [
  { id: 1, name: "节点1", pid: 0 },
  { id: 11, name: "节点1-1", pid: 1 },
  { id: 111, name: "节点1-1-1", pid: 11 },
  { id: 12, name: "节点1-2", pid: 1 },
  { id: 121, name: "节点1-2-1", pid: 12 },
  { id: 2, name: "节点2", pid: 0 },
  { id: 3, name: "节点3", pid: 0 },
  { id: 31, name: "节点3-1", pid: 3 },
  { id: 32, name: "节点3-2", pid: 3 },
];
/**
 * 数组转树形结构
 * @param list 源数组
 * @param tree 树
 * @param parentId 父ID
 */
const listToTree = (list, tree, parentId) => {
  list.forEach((item) => {
    // 判断是否为父级菜单
    if (item.parentId === parentId) {
      const child = {
        ...item,
        key: item.key || item.name,
        children: [],
      };
      // 迭代 list, 找到当前菜单相符合的所有子菜单
      listToTree(list, child.children, item.id);
      // 删掉不存在 children 值的属性
      if (child.children.length <= 0) {
        delete child.children;
      }
      // 加入到树中
      tree.push(child);
    }
  });
};

一维数组转树形结构(第三种,zTree.js 用的这种)

const listToTree = (
  nodes,
  setting = {
    key: "id",
    parentKey: "pid",
    childrenKey: "children",
  }
) => {
  if (!nodes || nodes.length === 0) return [];

  // 子节点
  let nodeChildren = (node, childrenKey, newChildren) => {
    if (typeof newChildren !== "undefined") {
      node[childrenKey] = newChildren;
    }
    return node[childrenKey];
  };

  // 声明变量
  let key = setting.key,
    parentKey = setting.parentKey,
    childrenKey = setting.childrenKey;
  let result = [];
  let tmpMap = {};
  // 获取所有节点的map
  for (let i = 0; i < nodes.length; i++) {
  // 如果源数据数组中有children,则需要删除掉,否则会导致和之前的children合并
    nodes[i][childrenKey] && delete nodes[i][childrenKey];
    tmpMap[nodes[i][key]] = nodes[i];
  }
  // 解析父子级
  for (let i = 0; i < nodes.length; i++) {
    let parent = tmpMap[nodes[i][parentKey]];
    if (parent && nodes[i][key] !== nodes[i][parentKey]) {
      let children = nodeChildren(parent, childrenKey);
      if (!children) {
        children = nodeChildren(parent, childrenKey, []);
      }
      children.push(nodes[i]);
    } else {
      result.push(nodes[i]);
    }
  }

  return result;
};

// 输出包含children层级关系的树形结构
console.log(listToTree(list, 0));

树形结构转一维数组

const treeToList = (nodes, childrenKey = "children") => {
  const res = [];
  for (let node of nodes) {
    res.push(node);
    if (node[childrenKey] && node[childrenKey].length) {
      let children = treeToSimpleData(node[childrenKey], childrenKey);
      if (children) {
        res.push(...children);
      }
    }
  }
  return res;
};

模糊搜索树形结构数据

这个方法搜索子节点时,可以把父节点也带出来

const filterTreeData = (value, filterKey = "name", treeData = []) => {
  if (!treeData) return [];
  let res = [];
  treeData.forEach((v) => {
    if (v[filterKey].includes(value)) {
      const children = filterTreeData(value, filterKey, v.children);
      const obj = {
        ...v,
        children,
      };
      res.push(obj);
    } else {
      if (v.children && v.children.length > 0) {
        const children = filterTreeData(value, filterKey, v.children);
        const obj = {
          ...v,
          children,
        };
        if (children && children.length > 0) {
          res.push(obj);
        }
      }
    }
  });

  return res;
};

递归遍历异步路由

/**
 * 根据权限 - 递归过滤异步路由
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = [];

  routes.forEach((route) => {
    const temp = { ...route };
    // 还可以在递归中拼接全路径
    if (hasPermission(roles, temp)) {
      if (temp.children) {
        temp.children = filterAsyncRoutes(temp.children, roles);
      }
      res.push(tmp);
    }
  });

  return res;
}

自动导入 vuex 的 modules 下所有文件

import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

const modulesFiles = require.context("./modules", true, /\.js$/);

const modules = modulesFiles.keys().reduce((modules, modulePath) => {
  const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, "$1");
  const value = modulesFiles(modulePath);
  modules[moduleName] = value.default;
  return modules;
}, {});

const store = new Vuex.Store({
  modules,
  getters,
});

export default store;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值