所谓奇淫技巧无非是js优雅的处理一些小事情。所以想学会一门语言一定要多读书,很多东西都来自于基础知识。所谓“万变不离其宗”亦是此意。
1、金钱数字格式化
- const ThousandNum = num => num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
- const money = ThousandNum(20190214);
- // money => "20,190,214"
2、获取URL参数
- // location.search = "?name=young&sex=male"
- const params = new URLSearchParams(location.search.replace(/\?/ig, ""));
- params.has("young"); // true
- params.get("sex"); // "male"
3、判断奇数偶数
- const OddEven = num => !!(num & 1) ? "odd" : "even";
- const num = OddEven(2);
- // num => "even"
4、过滤数组中的空值
- const arr = [undefined, null, "", 0, false, NaN, 1, 2].filter(Boolean);
- // arr => [1, 2]
5、判断数组中相同元素的个数
- const arr = [0, 1, 1, 2, 2, 2];
- const count = arr.reduce((t, c) => {
- t[c] = t[c] ? ++ t[c] : 1;
- return t;
- }, {});
- // count => { 0: 1, 1: 2, 2: 3 }
后期为大家持续更新。敬请期待!