1.0.3 • Published 1 year ago

self-common-fn v1.0.3

Weekly downloads
-
License
ISC
Repository
github
Last release
1 year ago

数组去重

const uniqueArr = arr => [...new Set(arr)];
console.log(uniqueArr(["前端", "js", "html", "js", "css", "html"]));
// ['前端', 'js', 'html', 'css']

url 中参数转为对象

const getParameters = URL =>
  JSON.parse(
    `{"${decodeURI(URL.split("?")[1])
      .replace(/"/g, '\\"')
      .replace(/&/g, '","')
      .replace(/=/g, '":"')}"}`
  );
getParameters("https://www.google.com.hk/search?q=js+md&newwindow=1");
// {q: 'js+md', newwindow: '1'}

检测对象是否为空

const isEmpty = obj => Reflect.ownKeys(obj).length === 0 && obj.constructor === Object;
isEmpty({}); // true
isEmpty({ a: "not empty" }); //false

生成随机 16 禁止

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

检查当前选项卡是否在后台 浏览器使用选项卡式浏览,任何网页都有可能在后台,此时对用户来说是没有在浏览的, 知道怎么快速检测到,你的网页对用户是隐藏还是可见吗?

const isTabActive = () => !document.hidden;
isTabActive();
// true|false

检测元素是否处于焦点

activeElement  属性返回文档中当前获得焦点的元素。
const elementIsInFocus = (el) => (el === document.activeElement);
elementIsInFocus(anyElement)
// 元素处于焦点返回 true,反之返回 false

检查设备类型 使用 navigator.userAgent  判断是移动设备还是电脑设备:

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

两日期之间相差的天数 日常开发中经常遇到需要显示剩余天数, 一般我们就需要计算两日期之间相差天数:

const dayDiff = (date1, date2) => Math.ceil(Math.abs(date1.getTime() - date2.getTime()) / 86400000);
dayDiff(new Date("2021-10-21"), new Date("2022-02-12"));
// Result: 114

将 RGB 转换为十六进制

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

1 year ago

1.0.2

1 year ago

1.0.1

1 year ago

1.0.0

1 year ago