js常用代码片段(更新中)

网上摘录常用js片段

时间戳转换为时间

function timestampToTime(timestamp = Date.parse(new Date()), isMs = true) {
  const date = new Date(timestamp * (isMs ? 1 : 1000));
  return `${date.getFullYear()}-${
    date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1
  }-${date.getDate()} ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`;
}

生成随机数

function randomNum(min, max) {
  switch (arguments.length) {
    case 1:
      return parseInt(Math.random() * min + 1, 10);
    case 2:
      return parseInt(Math.random() * (max - min + 1) + min, 10);
    default:
      return 0;
  }
}
// randomNum(1,10)

动态引入script

export const injectScript = (src) => {
    const s = document.createElement('script');
    s.type = 'text/javascript';
    s.async = true;
    s.src = src;
    const t = document.getElementsByTagName('script')[0];
    t.parentNode.insertBefore(s, t);
}

数组排序

export const sort = (arr, type = 1) => {
    return arr.sort((a, b) => {
        switch (type) {
            case 1:
                return a - b;
            case 2:
                return b - a;
            case 3:
                return Math.random() - 0.5;
            default:
                return arr;
        }
    })
}

转义html(防XSS攻击)

export const escapeHTML = str =>{
    str.replace(
        /[&<>'"]/g,
        tag =>
            ({
                '&': '&amp;',
                '<': '&lt;',
                '>': '&gt;',
                "'": '&#39;',
                '"': '&quot;'
            }[tag] || tag)
    );
};

reduce用法

from:https://segmentfault.com/a/1190000021737914

//数组成员位置记录
// const arr = [2, 1, 5, 4, 2, 1, 6, 6, 7];
// Position(arr, 2); // [0, 4]
function Position(arr = [], val) {
  return arr.reduce((t, v, i) => (v === val && t.push(i), t), [])
}
/*
回调函数(必选):(t, v, i) => (v === val && t.push(i), t):callback
	回调函数的参数:
		t:累计器完成计算的返回值(必选)
		v:当前元素(必选)
		i:当前元素索引(可选)
初始值(可选):[]:t的初始值
过程:
	以t作为累计结果的初始值,不设置t则以数组第一个元素为初始值
	开始遍历,使用累计器处理v(调用回调函数进行操作),将v的映射结果累计到t上,结束此次循环,返回t
	进入下一次循环,重复上述操作,直至数组最后一个元素
	结束遍历,返回最终的t
*/

数组技巧

// 数组克隆
const _arr = [0, 1, 2];
const arr = [..._arr];
// 数组合并
const arr1 = [0, 1, 2];
const arr2 = [3, 4, 5];
const arr = [...arr1, ...arr2];
// 数组去重
const arr = [...new Set([0, 1, 1, null, null])];
// 过滤空值 undefined、null、""、0、false、NaN
const arr = [undefined, null, "", 0, false, NaN, 1, 2].filter(Boolean);
// arr [1,2]

对象技巧

// 克隆对象
const _obj = { a: 0, b: 1, c: 2 }; // 以下方法任选一种
const obj = { ..._obj };
// 对象字面量
const env = "prod";
const link = {
    dev: "Development Address",
    test: "Testing Address",
    prod: "Production Address"
}[env];
// link => "Production Address"
// 解构对象属性默认值
const obj = { a: 0, b: 1, c: 2 };
const { a, b = 2, d = 3 } = obj;
// a b d => 0 1 3

js相关

最近在做动画相关的项目,推荐 11 个好用的 JS 动画库 - 爱前端不爱恋爱的文章 - 知乎 https://zhuanlan.zhihu.com/p/96628691

重温一下 JS 进阶需要掌握的 13 个概念 - 爱前端不爱恋爱的文章 - 知乎 https://zhuanlan.zhihu.com/p/94015790

原文地址:https://www.cnblogs.com/somegenki/p/13127490.html