- 深复制(Deep Copy)对象或数组
function deepCopy(obj: any) { if (typeof obj !== "object" || obj == null) { return obj; } let newObj: any = {}; if (Array.isArray(obj)) { newObj = []; } for (let key in obj) { newObj[key] = deepCopy(obj[key]); } return newObj; }
- 格式化日期
function formatDate(date: Date, format: string) { var o = { "M+": date.getMonth() + 1, //月份 "d+": date.getDate(), //日 "h+": date.getHours(), //小时 "m+": date.getMinutes(), //分 "s+": date.getSeconds(), //秒 "q+": Math.floor((date.getMonth() + 3) / 3), //季度 "S": date.getMilliseconds() //毫秒 }; if (/(y+)/.test(format)) { format = format.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length)); } for (var k in o) { if (new RegExp("(" + k + ")").test(format)) { format = format.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length))); } } return format; }
- 获取URL查询参数
function getQueryString(name: string) { var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"); var r = window.location.search.substr(1).match(reg); if (r != null) return decodeURIComponent(r[2]); return null; }
- 数组去重
function uniqueArray(arr: any[]) { return arr.filter((item, index) => { return arr.indexOf(item) === index; }); }
- 防抖和节流
// 防抖 function debounce(fn: Function, wait: number) { let timeout: any = null; return function() { let context = this; let args = arguments; if (timeout !== null) clearTimeout(timeout); timeout = setTimeout(() => { fn.apply(context, args); }, wait); }; } // 节流 function throttle(fn: Function, delay: number) { let last = 0; return function() { let context = this; let args = arguments; let now = new Date(); if (now - last > delay) { fn.apply(context, args); last = now; } }; }
pick()
方法:从一个对象中选取指定的属性,返回一个新对象。function pick<T extends object, K extends keyof T>(object: T, keys: K[]): Pick<T, K> { return keys.reduce((acc, key) => { if (object.hasOwnProperty(key)) { acc[key] = object[key]; } return acc; }, {} as Pick<T, K>); } interface Person { name: string; age: number; address: string; } const person: Person = { name: 'Tom', age: 30, address: '123 Main St.' }; const pickedPerson = pick(person, ['name', 'age']); console.log(pickedPerson); // { name: 'Tom', age: 30 }
omit()
方法:从一个对象中删除指定的属性,返回一个新对象。function omit<T extends object, K extends keyof T>(object: T, keys: K[]): Omit<T, K> { const filteredObject = Object.entries(object).filter(([key]) => !keys.includes(key as K)); return Object.fromEntries(filteredObject) as Omit<T, K>; } interface Person { name: string; age: number; address: string; } const person: Person = { name: 'Tom', age: 30, address: '123 Main St.' }; const omittedPerson = omit(person, ['address']); console.log(omittedPerson); // { name: 'Tom', age: 30 }
camelToSnake()
方法:将驼峰式命名的字符串转换为蛇形命名的字符串。function camelToSnake(camelCase: string): string { return camelCase.replace(/[A-Z]/g, match => `_${match.toLowerCase()}`); } console.log(camelToSnake('firstName')); // 'first_name' console.log(camelToSnake('phoneNumber')); // 'phone_number'
snakeToCamel()
方法:将蛇形命名的字符串转换为驼峰式命名的字符串。function snakeToCamel(snakeCase: string): string { return snakeCase.replace(/_\w/g, match => match[1].toUpperCase()); } console.log(snakeToCamel('first_name')); // 'firstName' console.log(snakeToCamel('phone_number')); // 'phoneNumber'
uniqueId()
方法:生成一个唯一的ID(基于当前时间)。function uniqueId(): string { return `${Date.now().toString(36)}-${Math.random().toString(36).substr(2, 9)}`; } console.log(uniqueId()); // '2lnditl-nd15na9j7' console.log(uniqueId()); // '2lndj94-nd15m60w2'
版权声明:
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若内容造成侵权、违法违规、事实不符,请将相关资料发送至xkadmin@xkablog.com进行投诉反馈,一经查实,立即处理!
转载请注明出处,原文链接:https://www.xkablog.com/typescriptbc/1188.html