我是瘦子

灵活运用 JavaScript 开发技巧

Array Skill

统计元素个数

1
2
3
4
5
6
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 }

快速创建数据列表

1
2
const data = new Array(5).fill({id: 1});
// data => [{id:1},{id:1},{id:1},{id:1},{id:1}]

Tips: fill() 方法用一个固定值填充一个数组中从起始索引到终止索引内的全部元素。不包括终止索引。

创建指定长度数组

1
2
const arr = [...new Array(5).keys()];
// arr => [0, 1, 2, 3, 4]

创建指定长度且值相等的数组

1
2
const arr = [...new Array(3).keys()].fill(0);
// arr => [0, 0, 0]

Object Skill

删除无用属性

1
2
3
const obj = { a: 0, b: 1, c: 2 }; // 只想拿b和c
const { a, ...rest } = obj;
// rest => { b: 1, c: 2 }

DOM Skill

显示全部 DOM 边框:调试页面元素边界时使用

1
2
3
[].forEach.call($$("*"), dom => {
dom.style.outline = "1px solid #" + (~~(Math.random() * (1 << 24))).toString(16);
});

Number Skill

取最小最大值

1
2
3
4
const arr = [0, 1, 2];
const min = Math.min(...arr);
const max = Math.max(...arr);
// min max => 0 2

String Skill

生成随机HEX色值

1
2
3
const randomColor = () => "#" + Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0");
const color = randomColor();
// color => "#f03665"

获取查询字符串参数

1
2
3
4
5
6
7
8
9
// Assuming "?post=1234&action=edit"

var urlParams = new URLSearchParams(window.location.search);

console.log(urlParams.has('post')); // true
console.log(urlParams.get('action')); // "edit"
console.log(urlParams.getAll('action')); // ["edit"]
console.log(urlParams.toString()); // "?post=1234&action=edit"
console.log(urlParams.append('active', '1')); // "?post=1234&action=edit&active=1"