JavaScript中的一些实用小方法

59 阅读1分钟

获取两个整数之间的随机整数

该方法用于获取两个整数之间的随机整数:

const random = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);

random(1, 50);

获取随机十六进制颜色

该方法用于获取一个随机的十六进制颜色值:

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

randomHex();

随机字符串

该方法用于生成一个随机的字符串,使用的是Math.random再转36进制。

const randomString = () => Math.random().toString(36).slice(2);

randomString();

检测系统是否是黑暗模式

该方法用于检测当前的环境是否是黑暗模式,它是一个布尔值:

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

console.log(isDarkMode)

去除字符串中的HTML

该方法用于去除字符串中的HTML元素,即获取一段html字符串内的文本

const stripHtml = html => (new DOMParser().parseFromString(html, 'text/html')).body.textContent || '';

获取随机布尔值(True/False)

该方法用于获取随机布尔值,使用Math.random() 会返回 0 到 1 的随机数,之后判断它是否大于 0.5,将会得到一个 50% 概率为 True 或 False 的值

const randomBoolean = () => Math.random() >= 0.5;
console.log(randomBoolean());

获取选中的文本

该方法通过内置的 getSelection 属性获取用户鼠标选中的文本::

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

getSelectedText();