CodeHelper CodeHelper
首页
JavaScript
PHP
Python
Git速查表 (opens new window)
博客 (opens new window)
首页
JavaScript
PHP
Python
Git速查表 (opens new window)
博客 (opens new window)
  • 开始

    • 使用
  • 函数方法

    • 字符串
    • 数字
    • 数组
      • 将数组转为对象(指定key)
      • 数组去重
      • 随机打乱数组(洗牌算法)
    • 日期时间
    • 缓存
    • 深浅拷贝
    • 正则
    • md5
    • 其它
  • 梳理

    • 循环
  • 高级操作

    • 类型转换技巧
    • 防抖与节流
    • Promise实现
目录

数组

# 将数组转为对象(指定key)

const arrayToObject = (arr, key) => arr.reduce((a, b) => ({ ...a, [b[key]]: b }), {});

// eg:
arrayToObject([{id:6,name:'张三'}, {id:70,name:'里斯'}], 'id')
/*
{
    "6": {
        "id": 6,
        "name": "张三"
    },
    "70": {
        "id": 70,
        "name": "里斯"
    }
}
*/

# 数组去重

export const unique = (arr) => {
  if (Array.hasOwnProperty('from')) { 
    return Array.from(new Set(arr));
  } else { 
    var n = {},
    r = []; 
    for (var i = 0; i < arr.length; i++) {
      if (!n[arr[i]]) { 
        n[arr[i]] = true;
        r.push(arr[i]);
      }
    }
    return r; 
  }
}

# 随机打乱数组(洗牌算法)

export const shuffle = (arr) => { 
  let result = [], random;
  while (arr.length > 0) { 
    random = Math.floor(Math.random() * arr.length);
    result.push(arr[random]);
    arr.splice(random, 1) ;
  } 
  return result;
}
上次更新: 2022/08/26, 17:06:25
数字
日期时间

← 数字 日期时间→

Theme by Vdoing | Copyright © 2022-2023 CodeHelper
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式