最实用的JavaScript一行代码

韩小韩
2022-09-01 / 6 评论 / 1,743 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2023年02月01日,已超过443天没有更新,若内容或图片失效,请留言反馈。

文字复制到剪贴板

const copyText = async (text) => await navigator.clipboard.writeText(text)
copyText('单行代码 前端世界')

获取字符串中的字符数

const characterCount = (str, char) => str.split(char).length - 1

检查对象是否为空

const isEmpty = obj => Reflect.ownKeys(obj).length === 0 && obj.constructor === Object

等待一段时间再执行

const wait = async (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds));

获取两个日期之间的日差

const daysBetween = (date1, date2) => Math.ceil(Math.abs(date1 - date2) / (1000 * 60 * 60 * 24))

检查设备上的触摸支持

const touchSupported = () => ('ontouchstart' in window || DocumentTouch && document instanceof DocumentTouch)

在元素后插入 HTML 字符串

const insertHTMLAfter = (html, el) => el.insertAdjacentHTML('afterend', html)

随机排列数组

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

获取随机布尔值

const getRandomBoolean = () => Math.random() >= 0.5

计算数组的平均值

const average = (arr) => arr.reduce((a, b) => a + b) / arr.length

查询某天是否为工作日

const isWeekday = (date) => date.getDay() % 6 !== 0;
isWeekday(new Date(2023, 02, 01))
// true

转换华氏/摄氏

// 将华氏温度转换为摄氏温度
const fahrenheitToCelsius = (fahrenheit) => (fahrenheit - 32) * 5/9;
fahrenheitToCelsius(50);
// 10

// 将摄氏温度转华氏温度
const celsiusToFahrenheit = (celsius) => celsius * 9/5 + 32;
celsiusToFahrenheit(100)
// 212

每隔4个空1格美团卷码

[..."088896520132"].reduce((res, itm, idx) => (res += idx % 4 === 1 ? `${itm} `: itm),'');
// 08 8896 5201 32

检查当前选项卡是否在后台

const isTabActive = () => !document.hidden; 

isTabActive()
// true|false

检查设备类型

const judgeDeviceType =
      () => /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|OperaMini/i.test(navigator.userAgent) ? 'Mobile' : 'PC';

judgeDeviceType()  // PC | Mobile

5

评论 (6)

取消
  1. 头像
    小张
    Windows 10 Windows 10 / Microsoft Edge Microsoft Edge 中国河南省移动

    大佬很厉害

    回复
    1. 头像
      韩小韩 作者
      Windows 10 Windows 10 / Google Chrome Google Chrome 中国江苏省南京市电信
      @ 小张

      哈哈哈哈谢谢夸奖表情

      回复
  2. 头像
    lenk
    Windows 10 Windows 10 / Google Chrome Google Chrome 中国江苏省移动

    学到了,厉害的博主

    回复
    1. 头像
      韩小韩 作者
      Mac OS X 10.15.7 Mac OS X 10.15.7 / Google Chrome Google Chrome 中国江苏省南京市移动
      @ lenk

      mua~~~表情

      回复
  3. 头像
    淄博测漏
    Windows 10 Windows 10 / Google Chrome Google Chrome 中国山东省淄博市联通

    感谢分享,赞一个

    回复
    1. 头像
      韩小韩 作者
      Windows 10 Windows 10 / Google Chrome Google Chrome 中国江苏省南京市电信
      @ 淄博测漏

      表情

      回复