- 1. 格式化金钱
- 2. 生成随机ID
- 3. 生成随机HEX色值
- 4. 生成星级评分
- 5. 操作URL查询参数
- 6. 取整(代替正数的Math.floor(),代替负数的Math.ceil())
- 7. 补零
- 8. 转数值 (只对null、”“、false、数值字符串有效)
- 9. 时间戳
- 10. 精确小数
- 11. 判断奇数和偶数
1. 格式化金钱
const ThousandNum = num => num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
const money = ThousandNum(20190214);
// money => "20,190,214"
2. 生成随机ID
const RandomId = len => Math.random().toString(36).substr(3, len);
const id = RandomId(10);
// id => "jg7zpgiqva"
3. 生成随机HEX色值
const RandomColor = () => "#" + Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0");
const color = RandomColor();
// color => "#f03665"
4. 生成星级评分
const StartScore = rate => "★★★★★☆☆☆☆☆".slice(5 - rate, 10 - rate);
const start = StartScore(3);
// start => "★★★"
5. 操作URL查询参数
const params = new URLSearchParams(location.search.replace(/\?/ig, "")); // location.search = "?name=young&sex=male"
params.has("young"); // true
params.get("sex"); // "male"
6. 取整(代替正数的Math.floor(),代替负数的Math.ceil())
const num1 = ~~ 1.69;
const num2 = 1.69 | 0;
const num3 = 1.69 >> 0;
// num1 num2 num3 => 1 1 1
7. 补零
const FillZero = (num, len) => num.toString().padStart(len, "0");
const num = FillZero(169, 5);
// num => "00169"
8. 转数值 (只对null、”“、false、数值字符串有效)
const num1 = +null;
const num2 = +"";
const num3 = +false;
const num4 = +"169";
// num1 num2 num3 num4 => 0 0 0 169
9. 时间戳
const timestamp = +new Date("2019-02-14");
// timestamp => 1550102400000
10. 精确小数
const RoundNum = (num, decimal) => Math.round(num * 10 ** decimal) / 10 ** decimal;
const num = RoundNum(1.69, 1);
// num => 1.7
11. 判断奇数和偶数
const OddEven = num => !!(num & 1) ? "odd" : "even";
const num = OddEven(2);
// num => "even"