首页 > 编程语言 >常用的JavaScript代码技巧 (一)字符串、数字

常用的JavaScript代码技巧 (一)字符串、数字

时间:2022-11-15 17:46:08浏览次数:43  
标签:10 const 技巧 min max JavaScript num 字符串 Math

一、字符串类

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/

标签:10,const,技巧,min,max,JavaScript,num,字符串,Math
From: https://www.cnblogs.com/juminxuan/p/16893237.html

相关文章