utils方法记录

整理一些用到的方法

1.生成随机字符串

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
* FunctionName: 生成随机字符串
* Author: tpf
* Description:
* param {*} len 字符串长度 默认6位
*/
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
/**
* FunctionName: 去除末尾小数
* Author: tpf
* Description:
* param {*} val 要处理的值
* param {*} precision 精度,最少保留几位小数 截取处理,非四舍五入
* 最多支持20位
* param {*} defaultValue 为空时返回的默认值
*/
export function ellipsisEndDecimal(val, precision, defaultValue = '0') {
if (!val && val !== 0) return defaultValue
// 转数字转字符串,去除NaN
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
/**
* FunctionName: 复制文本内容
* Author: tpf
* Description:
* param {*} id 要复制页面元素的id
*/
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
/**
* FunctionName: 获取数组中最小值至最大值范围
* Author: tpf
* Description:
* param {*} list 取值数组
* param {*} field 取值字段
* param {*} fixed 字段保留小数位 默认2位
* param {*} connector 链接符 默认~
*/
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)}`
}

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!