1. 获取文件后缀名
export function getExt(filename) {
if (typeof filename == 'string') {
if(!filename.includes('.')){return null}
return filename
.split('.')
.pop()
.toLowerCase()
} else {
throw new Error('文件名必须为字符串')
}
}
2. 复制内容到剪贴板
export function copyToBoard(value) {
const element = document.createElement('textarea')
document.body.appendChild(element)
element.value = value
element.select()
if (document.execCommand('copy')) {
document.execCommand('copy')
document.body.removeChild(element)
return true
}
document.body.removeChild(element)
return false
}
3. 生成随机字符串
export function uuid(length=8, chars='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') {
let result = ''
for (let i = length; i > 0; --i)
result += chars[Math.floor(Math.random() * chars.length)]
return result
}
4. 简单的深拷贝
export function deepCopy(obj) {
if (typeof obj != 'object') {
return obj
}
if (obj == null) {
return obj
}
return JSON.parse(JSON.stringify(obj))
}
5. 数组去重
export function uniqueArray(arr) {
if (!Array.isArray(arr)) {
throw new Error('The first parameter must be an array')
}
if (arr.length == 1) {
return arr
}
return [...new Set(arr)]
}
6. 对象转化为FormData对象
export function getFormData(object) {
const formData = new FormData()
Object.keys(object).forEach(key => {
const value = object[key]
if (Array.isArray(value)) {
value.forEach((subValue, i) =>
formData.append(key + `[${i}]`, subValue)
)
} else {
formData.append(key, object[key])
}
})
return formData
}
7. 保留到小数点以后n位
export function cutNumber(number, no = 2) {
if (typeof number != 'number') {
number = Number(number)
}
return Number(number.toFixed(no))
}
|