温馨提示:QQ登录和微信登录将于2023年7月15日下线,为了不影响你的正常使用,请尽快绑定邮箱,使用邮箱登录。操作方法:登录后点击右上角【会员中心】,再点击左边的【绑定邮箱】。

你好,欢迎来到js代码网。

微信登录邮箱登录

首页>前端开发> 常用的JavaScript代码技巧 (一)字符串、数字

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

  • 分类:前端开发
  • 时间:2022-04-16
  • 阅读:2081

作为一名前端程序员需要了解一些常用的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 每次运行可能不一样



点击查看:常用的JavaScript代码技巧 (二)布尔、数组

相关文章