JS常用工具函数集合🔧

2022 年 9 月 5 日 星期一
/
8

JS常用工具函数集合🔧

前言

这些都是网上收集的方法

验证器

传入的值是否是原始值(Primitive)

function isPrimitive(value: any): boolean {
  return (
    typeof value === 'string' ||
    typeof value === 'number' ||
    // $flow-disable-line
    typeof value === 'symbol' ||
    typeof value === 'boolean'
  )
}

传入的值是否为空

function isUndef(v: any): v is undefined | null {
  return v === undefined || v === null
}

传入的值是否是有效的数组索引

function isValidArrayIndex(val: any): boolean {
  const n = parseFloat(String(val))
  return n >= 0 && Math.floor(n) === n && isFinite(val)
}

传入 的值是否是Promise

function isPromise(val: any): val is Promise<any> {
  return (
    isDef(val) &&
    typeof val.then === 'function' &&
    typeof val.catch === 'function'
  )
}

获取 obj 的内部 [[Class]] 属性

const _toString = Object.prototype.toString

传入的值是否是普通对象

function isPlainObject(obj: any): boolean {
  return _toString.call(obj) === '[object Object]'
}

检查日期是否有效

const isDateValid = (...val) => !Number.isNaN(new Date(...val).valueOf());

isDateValid("December 17, 1995 03:24:00");
// Result: true

转换器

将类数组转换为真实数组

function toArray(list: any, start?: number): Array<any> {
  start = start || 0
  let i = list.length - start
  const ret: Array<any> = new Array(i)
  while (i--) {
    ret[i] = list[i + start]
  }
  return ret
}

将驼峰字符串转为连字符串

const hyphenateRE = /\B([A-Z])/g
export const hyphenate = cached((str: string): string => {
  return str.replace(hyphenateRE, '-$1').toLowerCase()
})

请输入: 结果:

{{result}}

将字符串首字母大写

const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1)

capitalize("follow for more")
// Result: Follow for more

实用工具

单次执行函数(once)

/**
 * Ensure a function is called only once.
 */
 export function once (fn: Function): Function {
  let called = false
  return function () {
    if (!called) {
      called = true
      fn.apply(this, arguments)
    }
  }
}

在输入框中如何判断网址是否正确

function isUrl(url) {
    try {
        new URL(url);
        return true;
    } catch(err){
         return false;
        }
}
监听一段html中的所有图片加载完成后进行其他操作
/**
 * 传入dom元素节点和html字符串,该promise函数功能:
   1. 解析html,并将其添加到context
   2. 等待图片资源加载完毕(错误)再进行决议(回调)
 * @param {String} htmlStr 
 * @param {Element} context 
 * @returns Promise
 */
const parseHtmlWithStabilizeImg = (htmlStr, context) => {
  return new Promise((resolve, reject) => {
    let tmp,
      nodes = []
    const safe = document.createDocumentFragment()
    tmp = safe.appendChild(document.createElement('div'))
    tmp.innerHTML = htmlStr.replace(rxhtmlTag, '<$1></$2>')
    const images = Array.from(safe.querySelectorAll('img'))
    const promises = images.map((node) => {
      return new Promise((resolve, reject) => {
        const loadImg = new Image()
        loadImg.src = node.src
        loadImg.onload = () => {
          resolve(node)
        }
        loadImg.onerror = () => {
          resolve(node)
        }
      })
    })
    merge(nodes, tmp.childNodes)
    Promise.all(promises)
      .then((res) => {
        context.innerHTML = ''
        for (let i = 0; i < nodes.length; i++) {
          context.appendChild(nodes[i])
        }
        resolve()
      })
      .catch((err) => {
        console.log(err)
        resolve()
      })
  })
}

获取浏览器cookie

const cookie = name => `; ${document.cookie}`.split(`; ${name}=`).pop().split(';').shift();

cookie('_ga');
// Result: "GA1.2.1929736587.1601974046"

清除所有cookie

const clearCookies = document.cookie.split(';').forEach(cookie => document.cookie = cookie.replace(/^ +/, '').replace(/=.\*/, `=;expires=${new Date(0).toUTCString()};path=/`));

将RGB转换为16进制

const rgbToHex = (r, g, b) =>
"#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);

rgbToHex(0, 51, 255);
// Result: #0033ff`

复制到剪切板

使用 navigator.clipboard.writeText 轻松将任何文本复制到剪贴板上

const copyToClipboard = (text) => navigator.clipboard.writeText(text);

copyToClipboard("Hello World");

给出一个日期,程序给出属于今年的哪一天

const dayOfYear = (date) =>
Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24);

dayOfYear(new Date());
// Result: 272

计算两个日期之间相差的天数

const dayDif = (date1, date2) => Math.ceil(Math.abs(date1.getTime() - date2.getTime()) / 86400000)

dayDif(new Date("2020-10-21"), new Date("2021-10-22"))
// Result: 366

生成随机16进制

const randomHex = () => `#${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0")}`;

console.log(randomHex());
// Result: #92b008

从URL中获取查询参数

const getParameters = (URL) => {
  URL = JSON.parse('{"' + decodeURI(URL.split("?")[1]).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"') +'"}');
  return JSON.stringify(URL);
  };
  
  getParameters(window.location)
  // Result: { search : "easy", page : 3 }

获取时分秒格式的字符串

const timeFromDate = date => date.toTimeString().slice(0, 8);

  console.log(timeFromDate(new Date(2021, 0, 10, 17, 30, 0)));
  // Result: "17:30:00"

回到顶部(常用于右下角快捷返回功能)

const goToTop = () => window.scrollTo(0, 0);

  goToTop();

获取用户选定的文本

const getSelectedText = () => window.getSelection().toString();

getSelectedText();

打乱数组

const shuffleArray = (arr) => arr.sort(() => 0.5 - Math.random());

console.log(shuffleArray([1, 2, 3, 4]));
// Result: [ 1, 4, 3, 2 ]

检查用户是否处于黑暗模式

const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches

console.log(isDarkMode) // Result: True or False

筛选出window对象中由开发者(或引入的第三方库)自定义的属性

function getCustomWindowProperties() {
  // 创建一个新的 iframe 来获取干净的 window 对象
  const iframe = document.createElement('iframe');
  document.body.appendChild(iframe);
  const cleanWindow = iframe.contentWindow;

  // 比较当前 window 对象和干净的 window 对象
  const customProperties = [];
  for (const prop in window) {
    if (!(prop in cleanWindow)) {
      customProperties.push(prop);
    }
  }

  // 清理:移除 iframe
  document.body.removeChild(iframe);

  return customProperties;
}


const customProperties = getCustomWindowProperties();
console.log(customProperties); // 输出由开发者添加的 window 属性列表

使用社交账号登录

  • Loading...
  • Loading...
  • Loading...
  • Loading...
  • Loading...