取整
代替正数的Math.floor(),代替负数的Math.ceil()
const num1 = ~~3.14; const num2 = 3.14 | 0; const num3 = 3.14 >> 0; console.log(num1, num2, num3); // 3 3 3
补零
const FillZero = (num, len) => num.toString().padStart(len, "0"); const num = FillZero(688, 5); console.log(num); // 00688
转数值
只对null、""、false、数值字符串有效
const num1 = +null; const num2 = +""; const num3 = +false; const num4 = +"688"; console.log(num1, num2, num3, num4); // 0 0 0 688
时间戳
const timestamp = +new Date("2022-06-08"); console.log(timestamp); // 1654646400000
精确小数
const RoundNum = (num, decimal) => Math.round(num * 10 ** decimal) / 10 ** decimal; const num = RoundNum(3.14, 1); console.log(num); // 3.1
判断奇偶
const OddEven = (num) => (!!(num & 1) ? "odd" : "even"); const num = OddEven(18); console.log(num); // even
取最小最大值
const arr = [11, 12, 13]; const min = Math.min(...arr); const max = Math.max(...arr); console.log(min, max); // 11 13
生成范围随机数
const RandomNum = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min; const num = RandomNum(2, 16); console.log(num); // 9