/*** 获取文件后缀名* @param {*} filename * @returns */
function getExt(filename) {if (typeof filename =='string') {return filename.split('.').pop().toLowerCase()} else {throw new Error('filename must be a string type');}
}console.log(getExt('tdt.video'));/*** 复制内容到剪切板* 原理:1、创建一个textare元素并调用select()方法选中* 2、document.execCommand('copy')方法,拷贝当前选中内容到剪切板 * @param {*} value * @returns */
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;
}// console.log(copyToBoard('tianditu'));/*** 休眠多少毫秒* @param {*} ms * @returns */
function sleep(ms) {return new Promise((resolve => setTimeout(resolve, ms)));
}const fetchData = async () => {await sleep(1000);
}/*** 生成随机字符串* @param {*} length * @param {*} chars * @returns */
function uuid(length, chars) {chars = chars || '0123456789abcdefghijklmnopqrstuvwxyz';length = length || 8;let result = '';for (let i = length; i > 0; --i) {result += chars[Math.floor(Math.random()*chars.length)]}return result;
}console.log(uuid());/*** 深拷贝* 只拷贝对象、数组、以及对象数组,对于大部分场景已经足够* @param {*} obj * @returns */
function deepCopy(obj) {if (typeof obj !== 'object') {return obj;}if (obj == null) {return obj;}return JSON.parse(JSON.stringify(obj));
}const person = { name: '前端', child: { name: 'javascript' } };
const person1 = deepCopy(person);
person1.name = '大前端';
person1.child.name = 'css';
console.log(person, person1);/*** 数组去重* @param {*} arr * @returns */
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)]
}console.log(uniqueArray([1, 2, 1, 2, 3, 4, 4, 3]));/*** 保留到小数点后n位* @param {*} number * @param {*} no * @returns */
function cutNumber(number, no = 2) {if (typeof number != 'number') {number = Number(number);}return Number(number.toFixed(no))
}console.log(cutNumber('123.4568'));/*** 将对象转化为FormData对象* @param {*} object * @returns */
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;
}const obj = { file: '11.json', size: '12MB', child: ['tdt', 'tianditu'] };
console.log(getFormData(obj));
详细解决方案
js 常用功能函数封装
热度:2 发布时间:2023-10-17 07:01:04.0
相关解决方案