
JavaScript 实用技巧
字符串
生成随机 ID
1
2Math.random().toString(36).substr(2);
// => "l10buc9ga8"
字符串翻转
1
2'hello world'.split('').reverse().join('');
// => 'dlrow olleh'
从 HTML 中获取内容
1
2
3
4
5function getTextInHTML (html) {
return new DOMParser().parseFromString(html, 'text/html').body.textContent || '';
}
getTextInHTML('<h2>Hello World</h2>');
// => 'Hello World'
数字
转数
1
2
3
4
5
6
7// 仅对 null、''、false、数字字符串有效
let num1 = +null;
let num2 = +'';
let num3 = +false;
let num4 = +'123';
let num5 = +new Date('2021-12-25');
// num1 num2 num3 num4 num5 => 0 0 0 123 1640390400000
直接取整
1
2
3
4
5
6
7
8
9
10
11
12// 可用于字符串
let num1 = ~~ 1.09;
let num2 = 2.19 | 0;
let num3 = 3.29 >> 0;
let num3 = 4.39 ^ 0;
// num1 num2 num3 num4 => 1 2 3 4
let num1 = ~~ -1.19;
let num2 = -2.29 | 0;
let num3 = -3.09 >> 0;
let num3 = -4.39 ^ 0;
// num1 num2 num3 num4 => -1 -2 -3 -4
零填充
1
2
3
4
5
6
7
8
9function fillZeroStart (num, len) {
return num.toString().padStart(len, '0');
}
// fillZeroStart(12345, 10) => '0000012345'
function fillZeroEnd (num, len) {
return num.toString().padEnd(len, '0');
}
// fillZeroEnd(12345, 10) => '1234500000'
判断奇偶数
1
2
3
4
5
6
7
8
9
10// 整数部分判断奇偶数
function OddEven(num) {
return !!(num & 1) ? 'odd' : 'even';
}
let num1 = OddEven(11);
let num2 = OddEven(-11);
let num3 = OddEven(12);
let num4 = OddEven(-12.1);
// num1 num2 num3 num4 => 'odd' 'odd' 'even' 'even'
生成范围随机数
1
2
3
4function RandomNum(min, max) {
Math.floor(Math.random() * (max - min + 1)) + min;
}
// RandomNum(1, 10) => 5
增加千分位符
1
2
3
4function thousandNum (num) {
return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
// thousandNum(123456.78) => '123,456.78'
转化为万、亿、万亿单位
1
2
3
4
5
6
7
8
9
10function numberFormat (value) {
let k = 10000;
let sizes = ['', '万', '亿', '万亿'];
if (value >= k) {
let i = Math.floor(Math.log(value) / Math.log(k));
return (value / Math.pow(k, i)).toFixed(2) + sizes[i];
}
return Number(value).toFixed(2);
}
// numberFormat(12345678) => '1234.57万'
时间
获取当前日期
1
new Date(new Date().toLocaleDateString());
数组
截断数组
1
2
3let arr = [0, 1, 2];
arr.length = 2; // arr.slice(0, 2);
// arr => [0, 1]
在数组开头插入元素
1
2
3
4
5let arr = [1, 2];
arr.unshift(0);
arr = [0].concat(arr);
arr = [0, ...arr];
// arr => [0, 1, 2]
在数组末尾插入元素
1
2
3
4
5
6let arr = [0, 1];
arr.push(2);
arr.concat(2);
arr[arr.length] = 2;
arr = [...arr, 2];
// arr => [0, 1, 2]
获取数组中随机元素
1
2
3let arr = [0, 1, 2, 3, 4, 5];
let randomItem = arr[Math.floor(Math.random() * arr.length)];
// randomItem => 4
创建指定长度的迭代元素数组
1
2let arr = [...new Array(3).keys()];
// arr => [0, 1, 2]
创建指定长度的相同元素数组
1
2let arr = new Array(3).fill(0);
// arr => [0, 1, 2]
交换数值
1
2
3
4
5
6
7
8
9
10
11
12
13
14let a = 0;
let b = 1;
[a, b] = [b, a];
// a b => 1 0
```(
### 数组排序
```javascript
let arr = [4, 1, 3, 2, 5].sort((a, b) => a - b) // 升序
// arr => [1, 2, 3, 4, 5]
let arr = [4, 1, 3, 2, 5].sort((a, b) => b - a); // 倒序
// arr => [5, 4, 3, 2, 1]
数组去重
1
2let arr = [...new Set([0, 1, 1, null, null])];
// arr => [0, 1, null]
数组混淆
1
2let arr = [0, 1, 2, 3, 4, 5].slice().sort(() => Math.random() - .5);
// arr => [3, 4, 0, 5, 1, 2]
计算数组元素出现的次数
1
2
3
4
5
6let arr = [0, 1, 1, 2, 2, 2];
let count = arr.reduce((t, v) => {
t[v] = t[v] ? ++t[v] : 1;
return t;
}, {});
// count => { 0: 1, 1: 2, 2: 3 }
求数组平均值
1
2
3let arr = [1, 2, 3, 4, 5]
let avg = arr.reduce((a, b) => a + b) / arr.length
// avg => 3
颜色
生成随机 HEX 颜色值
1
2'#' + Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0");
// => '#d6259c'
RGB 转 HEX 颜色
1
2
3
4function rgbToHex (r, g, b) {
return '#' + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
}
rgbToHex(52, 45, 125);