常用的JavaScript代码技巧 (一)字符串、数字
一、字符串类
1.比较时间
const time1 = "2022-03-05 10:00:00"; const time2 = "2022-03-05 10:00:01"; const overtime = time1 < time2; // overtime => true
2.货币格式
const ThousandNum = num => num.toString().replace(/B(?=(d{3})+(?!d))/g, ","); const cash = ThousandNum(100000000); // cash => 100,000,000
3.随机密码
const Randompass = len => Math.random().toString(36).substr(3, len); const pass = RandomId(8); // pass => "7nf6tgru"
4.随机HEX颜色值
const RandomColor = () => "#" + Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0"); const color = RandomColor(); // color => "##26330b"
5.评价星星
const StartScore = rate => "★★★★★☆☆☆☆☆".slice(5 - rate, 10 - rate); const start = StartScore(4); // start => ★★★★☆
6.获得URL参数
const url = new URL('https://example.com?name=tom&sex=male'); const params = new URLSearchParams(url.search.replace(/?/ig, "")); params.has('sex'); // true params.get("sex"); // "male"
二、数字类
1.数字处理,替代Math.floor() 和 Math.ceil()
const n1 = ~~ 1.19; const n2 = 2.29 | 0; const n3 = 3.39 >> 0; // n1 n2 n3 => 1 2 3
2.补零
const FillZero = (num, len) => num.toString().padStart(len, "0"); const num = FillZero(123, 5); // num => "00123"
3.转换成数值
const num1 = +null; const num2 = +""; const num3 = +false; const num4 = +"59"; // num1 num2 num3 num4 => 0 0 0 59
4.时间戳
const timestamp = +new Date("2022-03-07"); // timestamp => 1646611200000
5.小数
const RoundNum = (num, decimal) => Math.round(num * 10 ** decimal) / 10 ** decimal; const num = RoundNum(1.2345, 2); // num => 1.23
6.奇偶校验
const YEven = num => !!(num & 1) ? "no" : "yes"; const num = YEven(1); // num => "no" const num = YEven(2); // num => "yes"
7.获得最小值最大值
const arr = [0, 1, 2, 3]; const min = Math.min(...arr); const max = Math.max(...arr); // min max => 0 3
8.生成范围随机数
const RandomNum = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min; const num = RandomNum(1, 10); // 6 每次运行可能不一样
本文引用 https://www.jsdaima.com/
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 使用C#创建一个MCP客户端
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 按钮权限的设计及实现