1.生成0-99数组
const arr1 = (n) => new Array(n).fill(0).map((v, i) => i)
const arr2 = (n) => Array.from(new Array(n), (v, i) => i)
arr1(100) // 0 - 99数组
arr2(100) // 0 - 99数组
2. 随机打乱数组
const randomArr = list => list.sort(() => Math.random() - 0.5)
randomArr([0,1,2,3,4,5,6,7,8,9]) // 随机排列结果
3.数组去重
[...new Set([1,1,2,2,3,3])] // [1,2,3]
4.数组取交集
const intersection = (a, ...arr) => [...new Set(a)].filter((v) => arr.every((b) => b.includes(v)))
intersection([1, 2, 3, 4], [2, 3, 4, 7, 8], [1, 3, 4, 9])
5.返回数组中最大/最小元素的索引
const maxIndex = (arr) => arr.reduce((prev, curr, i, a) => (curr > a[prev] ? i : prev), 0);
maxIndex([1, 3, 9, 7, 5]); // 2
const minIndex = (arr) => arr.reduce((prev, curr, i, a) => (curr < a[prev] ? i : prev), 0)
minIndex([2, 5, 3, 4, 1, 0, 9]) // 5
6.取出数组中最接近数值
const closest = (arr, n) => arr.reduce((prev, curr) => (Math.abs(curr - n) < Math.abs(prev - n) ? curr : prev))
closest([29, 87, 8, 78, 97, 20, 75, 33, 24, 17], 50) // 33
7.矩阵行列交换
const transpose = (matrix) => matrix[0].map((col, i) => matrix.map((row) => row[i]));
transpose(
[ // [
[1, 2, 3], // [1, 4, 7],
[4, 5, 6], // [2, 5, 8],
[7, 8, 9], // [3, 6, 9],
] // ]
);
8.手机号码格式化
const formatPhone = (str, sign = '-') => str.replace(/(\W|\s)/g, "").split(/^(\d{3})(\d{4})(\d{4})$/).filter(item => item).join(sign)
formatPhone('13123456789') // '131-2345-6789'
formatPhone('13 1234 56 789', ' ') // '131 2345 6789'
9.补零
const replenishZero = (num, len, zero = 0) => num.toString().padStart(len, zero)
replenishZero(8, 2) // 08
10.删除无效属性
const removeNullUndefined = (obj) => Object.entries(obj).reduce((a, [k, v]) => (v == null ? a : ((a[k] = v), a)), {});
removeNullUndefined({name: '', age: undefined, sex: null}) // { name: '' }
11.字符串转对象
const strParse = (str) => JSON.parse(str.replace(/(\w+)\s*:/g, (_, p1) => `"${p1}":`).replace(/\'/g, "\""))
strParse('{name: "jack"}')
12.比较两个对象
const isEqual = (...objects) => objects.every(obj => JSON.stringify(obj) === JSON.stringify(objects[0]))
isEqual({name: 'jack'}, {name: 'jack'}) // true
isEqual({name: 'jack'}, {name: 'jack1'}, {name: 'jack'}) // false
13.颜色值16进制转rgb
const hexToRgb = hex => hex.replace(/^#?([a-f\d])([a-f\d])([a-f\d])$/i, (_, r, g, b) => `#${r}${r}${g}${g}${b}${b}`).substring(1).match(/.{2}/g).map((x) => parseInt(x, 16));
hexToRgb('#00ffff'); // [0, 255, 255]
hexToRgb('#0ff'); // [0, 255, 255]
14.生成uuid文章来源:https://www.toymoban.com/news/detail-544849.html
const uuid = (a) => (a ? (a ^ ((Math.random() * 16) >> (a / 4))).toString(16) : ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, uuid))
uuid()
15.强制延迟执行文章来源地址https://www.toymoban.com/news/detail-544849.html
const sleep = async (t) => new Promise((resolve) => setTimeout(resolve, t));
sleep(2000).then(() => {console.log('time')});
到了这里,关于常用单行代码集锦的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!