utils方法记录
整理一些用到的方法
1.生成随机字符串
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
export const creatRandomString = (len = 6) => { const str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' const res = [] for (let i = 0; i < len; i++) { const index = Math.floor(Math.random() * str.length) str[index] && res.push(str[index]) } return res.join('') }
|
2.去除末尾小数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
export function ellipsisEndDecimal(val, precision, defaultValue = '0') { if (!val && val !== 0) return defaultValue let value = Number(val) if (isNaN(value)) return defaultValue if (precision) { const list = value.toString().split('.') if (!list[1]) { list[1] = '00000000000000000000' } value = list[0] + '.' + list[1].substring(0, precision) return Number(value) } return value }
|
3.复制文本内容
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
export function copyText(id) { if (!id) return const copyDom = document.getElementById(id) if (!copyDom) { console.log('请给copyText方法传入合法ID') return } const nodeTypes = ['INPUT', 'TEXTAREA'] if (nodeTypes.includes(copyDom.nodeName)) { copyDom.select() } else { window.getSelection().selectAllChildren(copyDom) } document.execCommand('Copy') }
|
4.获取数组中最小值至最大值范围
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
export function getRangeValue({ list = [], field, fixed = 2, connector = '~' }) { const rangeList = list.map(item => item[field]).filter(Boolean) let max = Math.max(...rangeList), min = Math.min(...rangeList) if (!rangeList.length) { max = min = 0; } if (max == min) { return max.toFixed(fixed) } return `${min.toFixed(fixed)}${connector}${max.toFixed(fixed)}` }
|