18 个基本 JavaScript 方法代码片段

开发 前端
在我们的日常开发过程中,我们经常使用许多常见的 JavaScript 代码片段,例如复制内容或从 URL 中检索特定参数。

在我们的日常开发过程中,我们经常使用许多常见的 JavaScript 代码片段,例如复制内容或从 URL 中检索特定参数。

这些代码片段都有固定的实现,方便开发,今天我们来了解一下7个常用的代码片段。

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 properties
Object.keys(obj) // ['a', 'b', 'c', 'd']
//Object.values()
// Returns an array of all enumerable property values of the given object itself
Object.values(obj) // [1, 2, 3, 4]
//Object.entries()
// Returns an array of key-value pairs for the given object's own enumerable properties
Object.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') // true
obj.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 effect
console.log(result) // {a: 1, b: 4, c: 5}

总结

以上就是我今天想与你分享的全部内容,希望这些内容对你有所帮助。

责任编辑:华轩 来源: web前端开发
相关推荐

2023-07-17 15:28:03

JavaScrip开发

2023-09-03 16:46:09

Pandas工具

2023-10-09 14:48:06

2023-10-10 16:16:05

JavaScrip开发

2011-07-11 10:16:07

JavaScript

2023-05-22 15:53:06

JavaScrip代码素材

2023-12-26 14:28:08

JavaScript开发

2023-11-03 16:02:00

JavaScript开发

2023-06-16 16:34:25

JavaScripWeb 开发

2024-01-04 16:46:58

JavaScript开发

2024-08-02 17:19:36

2021-09-03 10:08:53

JavaScript开发 代码

2021-09-17 15:31:47

代码JavaScript数组

2023-06-13 15:15:02

JavaScript前端编程语言

2024-01-30 08:54:05

JavaScript技巧代码

2019-11-14 15:30:34

JavaScript代码前端

2020-12-07 08:01:59

JavaScript入门技巧

2011-11-23 09:21:43

jQuery

2023-10-12 15:02:21

PythonPandas数据分析

2022-06-08 08:55:15

JavaScript代码前端
点赞
收藏

51CTO技术栈公众号