当前位置:首页 > 科技  > 软件

18 个基本 JavaScript 方法代码片段

来源: 责编: 时间:2024-06-21 17:22:41 236观看
导读在我们的日常开发过程中,我们经常使用许多常见的 JavaScript 代码片段,例如复制内容或从 URL 中检索特定参数。这些代码片段都有固定的实现,方便开发,今天我们来了解一下7个常用的代码片段。1、函数节流/** Function thro

在我们的日常开发过程中,我们经常使用许多常见的 JavaScript 代码片段,例如复制内容或从 URL 中检索特定参数。HcV28资讯网——每日最新资讯28at.com

HcV28资讯网——每日最新资讯28at.com

这些代码片段都有固定的实现,方便开发,今天我们来了解一下7个常用的代码片段。HcV28资讯网——每日最新资讯28at.com

1、函数节流

/** Function throttling timer version */function throttle(callback: Function, delay: number) {   let timer: number | null   return function () {     if (timer) return     const args = arguments //Use closure to save parameter array     timer = setTimeout(() => {       callback.apply(null, args)       timer = null     }, delay)   }}

2、URL 解码和编码

/** Encode URL */function encodeURL(url: string, isComponent = true): string {   return isComponent ? encodeURIComponent(url) : encodeURI(url)}/** Decode URL */function decodeURL(url: string, isComponent = true): string {   return isComponent ? decodeURIComponent(url) : decodeURI(url)}

3、使用JavaScript 获取全局 CSS 变量

/** * @description Use JS to get global css variables * @param cssVariableName variable name * @returns {string} variable value*/function getCssVariableValue(cssVariableName: string): string {   return getComputedStyle(document.documentElement).getPropertyValue(cssVariableName)}

4、使用 JS 设置全局 CSS 变量

/**  * @description Set global CSS variables with JS  * @param {string} cssVariableName variable name  * @param {string} cssVariableValue variable value  */function setCssVariableValue(cssVariableName: string, cssVariableValue: string): void {   document.documentElement.style.setProperty(cssVariableName, cssVariableValue)}

5、清除所有 cookies 

/** * @description clear all cookies */function clearCookie(): void {   const keyList = document.cookie.match(/[^ =;]+(?=/=)/g) as string[] | null   keyList && keyList.forEach(key => (document.cookie = `${key}=0;path=/;expires=${new Date(0).toUTCString()}`))}

6、清除所有项目缓存

/** * @description Clear all project caches */function clearCache(): void {  window.localStorage.clear()  window.sessionStorage.clear()  const keyList = document.cookie.match(/[^ =;]+(?=/=)/g) as string[] | null  keyList && keyList.forEach(key => (document.cookie = `${key}=0;path=/;expires=${new Date(0).toUTCString()}`))}

7、通过名称获取 URL 查询参数 

/**  * @description Get URL query parameters by name  * @param {string} key The key of the query parameter that needs to be obtained  * @param {string} url The link that needs to be parsed, the default is window.location.href  * @returns {string | null} obtained value corresponding to key  */function getQueryByName(key, url = window.location.href) {   const queryNameRegExp = new RegExp(`[?&]${key}=([^&]*)(?:&|$)`)   const queryNameMatch = url.match(queryNameRegExp)   return queryNameMatch ? decodeURIComponent(queryNameMatch[1]) : null}

8、登录页面时间前缀

/**  * @description time prefix of login page  * @returns {string} time prefix  */function timeFix(): string {   const time = new Date()   const hour = time.getHours()   return hour < 9 ? 'Good morning' : hour <= 11 ? 'Good morning' : hour <= 13 ? 'Good afternoon' : hour < 20 ? 'Good afternoon' : 'Good evening'}

9、登录页面上的欢迎信息

/**  * @description Welcome message on the login page  * @returns {string} random welcome message  */function welcome(): string {   const list = ['Long time no see, I miss you so much! ', 'Wait until the stars go to sleep before I miss you', 'We are open today']   return list[Math.floor(Math.random() * list.length)]}

10、递归深层复制

/**  * @description Make a deep copy of the incoming data and return it  * @param {any} source data source  * @returns {any} copied data  */function deepClone(source: any): any {   if (!source || typeof source !== 'object') return source   if (source instanceof Date) return new Date(source)   if (source instanceof RegExp) return new RegExp(source)   const target = Array.isArray(source) ? ([] as Record<any, any>) : ({} as Record<any, any>)   for (const key in source) target[key] = typeof source[key] === 'object' ? deepClone(source[key]) : source[key]   return target}

11、随机生成一个 UUID 

/**  * @description Randomly generate a UUID  * @returns {string} generated uuid  */function getRandomUUID(): string {   const tempURL = URL.createObjectURL(new Blob())   const uuidStr = tempURL.toString()   const separator = uuidStr.includes('/') ? '/' : ':'   URL.revokeObjectURL(tempURL)   return uuidStr.substring(uuidStr.lastIndexOf(separator) + 1)}function getRandomUUID(): string {   const fn = (): string => (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)   return fn() + fn() + '-' + fn() + '-' + fn() + '-' + fn() + '-' + fn() + fn() + fn()}

12、随机布尔值

/**  * @description random boolean value  * @returns {boolean} true | false  */function getRandomBoolean(): boolean {   return Math.random() > 0.5}

13、反转字符串

/**  * @description reverse string  * @param {string} str string  * @returns {string} reversed string  */function reverseString(str: string): string {   return str.split('').reverse().join('')}

14、随机生成十六进制颜色

/**  * @description Randomly generates a color string in Hex format  * @returns {string} Color string in Hex format  */function getRandomHexColor(): string {   return `#${Math.floor(Math.random() * 0xffffff).toString(16)}`}

15、获取变量的真实类型

/**  * @description Get the real type of the variable  * @param {any} variable variable of any type  * @returns {string} variable type  */function getRawType(variable: any): string {   return Object.prototype.toString.call(variable).split(' ')[1].replace(']', '').toLowerCase()}

16、将文本复制到剪贴板

/**  * @description Copy text to clipboard  * @param {string} text The copied text  */function copyText(text: string): void {   // Whether to support navigator.clipboard attribute   const isClipboardApiSupported = window.navigator && window.navigator.clipboard   if (isClipboardApiSupported) {     window.navigator.clipboard.writeText(text)   } else {     const textarea = document.createElement('textarea')     textarea.readOnly = true     textarea.value = text     textarea.style.position = 'absolute'     textarea.style.top = '-9999px'     textarea.style.left = '-9999px'     document.body.appendChild(textarea)     textarea.select()     document.execCommand('copy')     textarea.remove()   }}

17、滚动到顶部

/**  * @description scroll to top  */function scrollToTop(element: HTMLElement): void {   element.scrollIntoView({ behavior: 'smooth', block: 'start' })}

18、对象通用方法

const obj = { a: 1, b: 2, c: 3, d: 4 }//Object.keys()// Will return an array consisting of the given object's own enumerable propertiesObject.keys(obj) // ['a', 'b', 'c', 'd']//Object.values()// Returns an array of all enumerable property values of the given object itselfObject.values(obj) // [1, 2, 3, 4]//Object.entries()// Returns an array of key-value pairs for the given object's own enumerable propertiesObject.entries(obj) // [['a', 1], ['b', 2], ['c', 3], ['d', 4]]//Object.fromEntries()//Convert the list of key-value pairs into an object, which is the reverse operation of Object.entries()Object.fromEntries( [['a', 1], ['b', 2]]) // { a: 1, b: 2 }// hasOwnProperty()// Returns a Boolean value indicating whether the object has the specified attribute in its own properties (that is, whether it has the specified key)obj.hasOwnProperty('a') // trueobj.hasOwnProperty('fff') // false//Object.assign()// Used to copy the values of all enumerable properties from one or more source objects to the target object. It will return the target object.const target = { a: 1, b: 2 }const source = { b: 4, c: 5 }const result = Object.assign(target, source) // { ...target, ...source } has the same effectconsole.log(result) // {a: 1, b: 4, c: 5}

总结

以上就是我今天想与你分享的全部内容,希望这些内容对你有所帮助。HcV28资讯网——每日最新资讯28at.com

本文链接:http://www.28at.com/showinfo-26-95546-0.html18 个基本 JavaScript 方法代码片段

声明:本网页内容旨在传播知识,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。邮件:2376512515@qq.com

上一篇: 盘点JavaScript focus/blur(聚焦)实际应用

下一篇: Python十个常用的自动化脚本

标签:
  • 热门焦点
  • 如何通过Python线程池实现异步编程?

    线程池的概念和基本原理线程池是一种并发处理机制,它可以在程序启动时创建一组线程,并将它们置于等待任务的状态。当任务到达时,线程池中的某个线程会被唤醒并执行任务,执行完任
  • 三万字盘点 Spring 九大核心基础功能

    大家好,我是三友~~今天来跟大家聊一聊Spring的9大核心基础功能。话不多说,先上目录:图片友情提示,本文过长,建议收藏,嘿嘿嘿!一、资源管理资源管理是Spring的一个核心的基础功能,不
  • 得物宠物生意「狂飙」,发力“它经济”

    作者|花花小萌主近日,得物宣布正式上线宠物鉴别,通过得物App内的&ldquo;在线鉴别&rdquo;,可找到鉴别宠物的选项。通过上传自家宠物的部位细节,就能收获拥有专业资质认证的得物鉴
  • 猿辅导与新东方的两种“归途”

    作者|卓心月 出品|零态LT(ID:LingTai_LT)如何成为一家伟大企业?答案一定是对&ldquo;势&rdquo;的把握,这其中最关键的当属对企业战略的制定,且能够站在未来看现在,即使这其中的
  • 大厂卷向扁平化

    来源:新熵作者丨南枝 编辑丨月见大厂职级不香了。俗话说,兵无常势,水无常形,互联网企业调整职级体系并不稀奇。7月13日,淘宝天猫集团启动了近年来最大的人力制度改革,目前已形成一
  • 造车两年股价跌六成,小米的估值逻辑变了吗?

    如果从小米官宣造车后的首个交易日起持有小米集团的股票,那么截至2023年上半年最后一个交易日,投资者将浮亏59.16%,同区间的恒生科技指数跌幅为52.78%
  • 3699元!iQOO Neo8 Pro顶配版今日首销:1TB UFS 4.0同价位唯一

    5月23日,iQOO推出了全新的iQOO Neo8系列,包含iQOO Neo8和iQOO Neo8 Pro两个版本,其中标准版搭载高通骁龙8+,而Pro版更是首发搭载了联发科天玑9200+旗舰
  • 最薄的14英寸游戏笔记本电脑 Alienware X14已可以购买

    2022年1月份在国际消费电子展(CES2022)上首次亮相的Alienware新品——Alienware X14现在已经可以购买了,这款笔记本电脑被誉为世界上最薄的 14 英寸游戏笔
  • 荣耀Magic4 至臻版 首创智慧隐私通话 强劲影音系统

    2022年第一季度临近尾声,在该季度内,许多品牌陆续发布自己的最新产品,让大家从全新的角度来了解当今的手机技术。手机是电子设备中,更新迭代十分迅速的一款产品,基
Top