当前位置:网站首页 > TypeScript编程 > 正文

TypeScript编程中常用的通用方法_typescript 教程

  1. 深复制(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; }
  2. 格式化日期
    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; }
  3. 获取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; }
  4. 数组去重
    function uniqueArray(arr: any[]) { return arr.filter((item, index) => { return arr.indexOf(item) === index; }); }
  5. 防抖和节流
    // 防抖 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; } }; }
  6. 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 }
  7. 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 }
  8. 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'
  9. 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'
  10. 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'

版权声明


相关文章:

  • typescript implements_typescript有必要学吗2024-10-30 13:16:42
  • typescript namespace module_编程项目2024-10-30 13:16:42
  • typescript基础语法_深入理解typescript2024-10-30 13:16:42
  • typescript教程视频_typescript入门教程2024-10-30 13:16:42
  • typescript写法_typescript入门教程2024-10-30 13:16:42
  • TypeScript入门案例2024-10-30 13:16:42
  • 【前端-TypeScript】TypeScript学习思维导图-一图看完《TypeScript编程》2024-10-30 13:16:42
  • typescript的作用_typescript有必要学吗2024-10-30 13:16:42
  • typescript interface和type的区别_typescript高级类型声明2024-10-30 13:16:42
  • typescript总结_web前端论文2024-10-30 13:16:42
  • 全屏图片