1. 多变量赋值
const [test1, test2, test3] = [1, 2, 3];
2. 替换switch
const data = {
a: callback,
b: callback,
c: callback,
};
data[something] && data[something]();
3. 短路运算
let arr;
(arr || [ ]).length
----------------
return res.data.data || 'no data'
----------------
isLoggedin && goToHomepage();
4. 变量交换
let x = 'Hello', y = 55;
const temp = x;
x = y;
y = temp;
[x, y] = [y, x];
5. 对象、数组合并
const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1, d: 4 };
obj2.a = 3;
obj1.a
Object.assign(obj3, obj1);
obj3.b = 10;
obj1.b
---------------
const arr1 = [20, 30];
const arr2 = arr1.concat(10, [60, 80]);
const arr3 = [...arr1, 10, 60, 80];
6. 序列生成/数组初始化
function Range(start, stop, step) {
return Array.from({ length: (stop- start) / step + 1}, (_, i) => start + (i * step));
}
Range('A'.charCodeAt(0), 'Z'.charCodeAt(0), 1).map((x) => String.fromCharCode(x))
------------------
Array.from({length: 5}, (item, index) => index)
7. 平均值计算
const average = (...args) => args.reduce((a, b) => a + b) / args.length;
average(1, 2, 3, 4);
8. 复制文本到剪贴板
navigator.clipboard.writeText(text)'
9. 随机数生成
const randomHex = () => `#${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0")}`;
randomHex();
---------------------
const randomString = (len) => {
const chars = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz123456789";
const strLen = chars.length;
let randomStr = "";
for (let i = 0; i < len; i++) {
randomStr += chars.charAt(Math.floor(Math.random() * strLen));
}
return randomStr;
};
randomString(10)
---------------
const randomNum = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
randomNum(1, 10)
10. 数组乱序(洗牌)
const shuffleArray = (arr) => arr.sort(() => Math.random() - 0.5)
shuffleArray([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
11. 全屏
const goToFullScreen = (element) => {
if (element.requestFullscreen) {
element.requestFullscreen();
} else if (element.mozRequestFullScreen) {
element.mozRequestFullScreen();
} else if (element.msRequestFullscreen) {
element.msRequestFullscreen();
} else if (element.webkitRequestFullscreen) {
element.webkitRequestFullScreen();
}
};
document.exitFullscreen();
12. 类型判断
const isType = (type) => (target) => `[object ${type[0].toUpperCase()}${type.slice(1)}]` === Object.prototype.toString.call(target);
const isArray = isType('array');
const isFunction = isType('Function');
isArray([]);
isFunction(function foo() {});
13. queryParams提取
const url = 'https://juejin.cn/flash-note/list?note_id=7140530613261434916&from=6&editing=1';
const getParams = (url) => JSON.parse(`{"${decodeURI(url.split('?')[1]).replace(/=/g, '":"').replace(/&/g, '","')}}`);
getParams(url);
14. 判定数组/对象是否为空
const isNotEmpty = (arr) => arr?.some((x) => x);
const isNotEmpty = (arr) => Array.isArray(arr) && arr.length > 0;
const isNotEmpty = (obj) => Reflect.ownKeys(obj).length === 0 && object.constructor === Object;
15. 数组排序
const list = ['Delta', 'alpha', 'ALPHA', 'CHARLIE', 'bravo'];
list.sort((a, b) => +(a.toLowerCase() > b.toLowerCase()) || +(a.toLowerCase() === b.toLowerCase()) - 1);
list.sort((a, b) => +(a.toLowerCase() < b.toLowerCase()) || +(a.toLowerCase() === b.toLowerCase()) - 1);
16. json-map转换
const jsonToMap = (json) => new Map(Object.entries(JSON.parse(json)));
const json = '{"user1":"John","user2":"Kate","user3":"Peter"}';
const map = jsonToMap(json);
const mapToJson = (map) => JSON.stringify(Object.fromEntries(map));
const map = new Map([ ['user1', 'John'], ['user2', 'Kate'], ['user3', 'Peter'],]);
const json = mapToJson(map);
17. 树形结构查找满足条件的子节点
const data = [
{
id: '11',
name: 'text11',
children: [
{
id: '111',
name: 'text111',
children: [],
},
],
},
{
id: '22',
name: 'text22',
children: [],
},
];
function findNode(tree, func) {
for (const node of tree) {
if (func(node)) return node;
if (node.children && node.children.length) {
const res = findNode(node.children, func);
if (res) return res;
}
}
return null;
}
findNode(data, (id) => id === '111')