Products
GG网络技术分享 2025-03-18 16:13 0
作为一名前端程序员需要了解一些常用的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"
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;
待续................
今天小编为大家分享生成1到100的随机数JavaScript教程。
js生成随机数使用math.random()函数
Math.random()
具体实现:
1、定义一个random()函数,原理是随机数和最大值减最小值的差相乘最后再加上最小值。
functionrandom(min,max){
returnMath.floor(Math.random()*(max-min))+min;
}
2、使用方法
for(vari=1;i<=10;i++){
console.log(random(1,100));
}
3、效果图
以上就是js生成1到100的随机数的详细内容,更多请关注WPMEE网站。
Demand feedback