讓你減少加班的15條高效JS技巧!記得收藏哦

来源:https://www.cnblogs.com/coderhf/archive/2020/06/29/13210179.html
-Advertisement-
Play Games

延遲函數delay const delay = ms => new Promise((resolve, reject) => setTimeout(resolve, ms)) ​ const getData = status => new Promise((resolve, reject) => { ...


延遲函數delay

 const delay = ms => new Promise((resolve, reject) => setTimeout(resolve, ms))
 ​
 const getData = status => new Promise((resolve, reject) => {
     status ? resolve('done') : reject('fail')
 })
 const getRes = async (data) => {
     try {
         const res = await getData(data)
         const timestamp = new Date().getTime()
         await delay(1000)
         console.log(res, new Date().getTime() - timestamp)
     } catch (error) {
         console.log(error)
     }
 }
 getRes(true) // 隔了1秒

 

分割指定長度的元素數組

 const listChunk = (list, size = 1, cacheList = []) => {
     const tmp = [...list]
     if (size <= 0) {
         return cacheList
     }
     while (tmp.length) {
         cacheList.push(tmp.splice(0, size))
     }
     return cacheList
 }
 ​
 console.log(listChunk([1, 2, 3, 4, 5, 6, 7, 8, 9])) // [[1], [2], [3], [4], [5], [6], [7], [8], [9]]
 console.log(listChunk([1, 2, 3, 4, 5, 6, 7, 8, 9], 3)) // [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
 console.log(listChunk([1, 2, 3, 4, 5, 6, 7, 8, 9], 0)) // []
 console.log(listChunk([1, 2, 3, 4, 5, 6, 7, 8, 9], -1)) // []

 

獲取數組交集

 const intersection = (list, ...args) => list.filter(item => args.every(list => list.includes(item)))
 ​
 console.log(intersection([2, 1], [2, 3])) // [2]
 console.log(intersection([1, 2], [3, 4])) // []

 

函數柯里化

 const curring = fn => {
     const { length } = fn
     const curried = (...args) => {
         return (args.length >= length
               ? fn(...args)
               : (...args2) => curried(...args.concat(args2)))
     }
     return curried
 }
 ​
 const listMerge = (a, b, c) => [a, b, c]
 const curried = curring(listMerge)
 console.log(curried(1)(2)(3)) // [1, 2, 3]
 ​
 console.log(curried(1, 2)(3)) // [1, 2, 3]
 ​
 console.log(curried(1, 2, 3)) // [1, 2, 3]

 

字元串前面空格去除與替換

 const trimStart = str => str.replace(new RegExp('^([\\s]*)(.*)$'), '$2')
 console.log(trimStart(' abc ')) // abc  
 console.log(trimStart('123 ')) // 123  

 

字元串後面空格去除與替換

 const trimEnd = str => str.replace(new RegExp('^(.*?)([\\s]*)$'), '$1')
 console.log(trimEnd(' abc ')) //   abc  
 console.log(trimEnd('123 ')) // 123  

 

獲取當前子元素是其父元素下子元素的排位

 const getIndex = el => {
     if (!el) {
         return -1
     }
     let index = 0
     do {
         index++
     } while (el = el.previousElementSibling);
     return index
 }

 

獲取當前元素相對於document的偏移量

 const getOffset = el => {
     const {
         top,
         left
     } = el.getBoundingClientRect()
     const {
         scrollTop,
         scrollLeft
     } = document.body
     return {
         top: top + scrollTop,
         left: left + scrollLeft
     }
 }

 

獲取元素類型

 const dataType = obj => Object.prototype.toString.call(obj).replace(/^\[object (.+)\]$/, '$1').toLowerCase();

 

判斷是否是移動端

 const isMobile = () => 'ontouchstart' in window

 

fade動畫

 const fade = (el, type = 'in') {
     el.style.opacity = (type === 'in' ? 0 : 1)
     let last = +new Date()
     const tick = () => {
         const opacityValue = (type === 'in' 
                             ? (new Date() - last) / 400
                             : -(new Date() - last) / 400)
         el.style.opacity = +el.style.opacity + opacityValue
         last = +new Date()
         if (type === 'in'
           ? (+el.style.opacity < 1)
           : (+el.style.opacity > 0)) {
             requestAnimationFrame(tick)
         }
     }
     tick()
 }

 

將指定格式的字元串解析為日期字元串

 const dataPattern = (str, format = '-') => {
     if (!str) {
         return new Date()
     }
     const dateReg = new RegExp(`^(\\d{2})${format}(\\d{2})${format}(\\d{4})$`)
     const [, month, day, year] = dateReg.exec(str)
     return new Date(`${month}, ${day} ${year}`)
 } 
 ​
 console.log(dataPattern('12-25-1995')) // Mon Dec 25 1995 00:00:00 GMT+0800 (中國標準時間)

 

禁止網頁複製粘貼

 const html = document.querySelector('html')
 html.oncopy = () => false
 html.onpaste = () => false

 

### input框限制只能輸入中文

 const input = document.querySelector('input[type="text"]')
 const clearText = target => {
     const {
         value
     } = target
     target.value = value.replace(/[^\u4e00-\u9fa5]/g, '')
 }
 input.onfocus = ({target}) => {
     clearText(target)
 }
 input.onkeyup = ({target}) => {
     clearText(target)
 }
 input.onblur = ({target}) => {
     clearText(target)
 }
 input.oninput = ({target}) => {
     clearText(target)
 }

 

去除字元串中的html代碼

 const removeHTML = (str = '') => str.replace(/<[\/\!]*[^<>]*>/ig, '')
 console.log(removeHTML('<h1>哈哈哈哈<呵呵呵</h1>')) // 哈哈哈哈<呵呵呵

 

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 在開發好用戶標簽以後,如何將標簽應用到實際其實是一個很重要的問題。只有做好產品的設計才能讓標簽發揮真正的價值,本文將介紹用戶畫像的產品化過程。 一、標簽展示 首先是標簽展示功能,這個主要供業務人員和研發人員使用,是為了更直觀的看見整個的用戶標簽體系。 不同的標簽體系會有不同的層級,那麼這個頁面的設計 ...
  • Android自家的,又可以省去findviewbyid(),而且Butterknife上大神都已經推薦使用的,還有什麼理由不去改寫呢。build.gradle中開啟viewBinding功能。Activity 綁定private lateinit var mBinding: ActivityEbo... ...
  • 原文鏈接:https://www.cnblogs.com/qiyer/、https://www.cnblogs.com/qiyer/p/7442680.html ...
  • 序言 疫情基本控制,同時面試也漸漸開始了,以下iOS面試題僅供參考,畢竟面試是不可控的,但懂得越多,自然機會越大! 位元組一面內容: 1、 自我介紹 2、 介紹一下簡歷中的一個項目 3、 面向對象的三個要素 4、 多態? 5、 Java,python,OC運行效率孰高? 6、 Property,其中c ...
  • 新聞 谷歌發佈全新AR技術 單攝像頭即可實現AR景深感應 谷歌發佈首款基於Android 11開發者預覽版的Android TV版 代號“sabrina”:新Android TV電視棒將採用鵝卵石造型 Android 12曝光:谷歌欲全面拋棄對32位的支持 Android 11中的“對話”功能可能不 ...
  • Android app 本地設置信息的保存與調用。preferences.getString後面的文本是調用失敗後的預設顯示值。儲存值一定要實例化一個Editor出來,如果直接使用.edit().putString()不是不可以,但會每次調用都多出一個實例。最後記得要editor.apply()執行... ...
  • 基本類型(棧數據) String Number Boolean null undefined symbol(ES6) 引用類型(堆數據) Array Object Function Date RegExp 等 區分 棧小堆大 1.基礎類型是放置在棧裡面,一般基礎類型的數據都比較小,賦值不影響自身 v ...
  • vue是數據驅動視圖更新的框架, 所以對於vue來說組件間的數據通信非常重要,那麼組件之間如何進行數據通信的呢? 首先我們需要知道在vue中組件之間存在什麼樣的關係, 才更容易理解他們的通信方式, 就好像過年回家,坐著一屋子的陌生人,相互之間怎麼稱呼,這時就需要先知道自己和他們之間是什麼樣的關係。 ...
一周排行
    -Advertisement-
    Play Games
  • 概述:在C#中,++i和i++都是自增運算符,其中++i先增加值再返回,而i++先返回值再增加。應用場景根據需求選擇,首碼適合先增後用,尾碼適合先用後增。詳細示例提供清晰的代碼演示這兩者的操作時機和實際應用。 在C#中,++i 和 i++ 都是自增運算符,但它們在操作上有細微的差異,主要體現在操作的 ...
  • 上次發佈了:Taurus.MVC 性能壓力測試(ap 壓測 和 linux 下wrk 壓測):.NET Core 版本,今天計劃準備壓測一下 .NET 版本,來測試並記錄一下 Taurus.MVC 框架在 .NET 版本的性能,以便後續持續優化改進。 為了方便對比,本文章的電腦環境和測試思路,儘量和... ...
  • .NET WebAPI作為一種構建RESTful服務的強大工具,為開發者提供了便捷的方式來定義、處理HTTP請求並返迴響應。在設計API介面時,正確地接收和解析客戶端發送的數據至關重要。.NET WebAPI提供了一系列特性,如[FromRoute]、[FromQuery]和[FromBody],用 ...
  • 原因:我之所以想做這個項目,是因為在之前查找關於C#/WPF相關資料時,我發現講解圖像濾鏡的資源非常稀缺。此外,我註意到許多現有的開源庫主要基於CPU進行圖像渲染。這種方式在處理大量圖像時,會導致CPU的渲染負擔過重。因此,我將在下文中介紹如何通過GPU渲染來有效實現圖像的各種濾鏡效果。 生成的效果 ...
  • 引言 上一章我們介紹了在xUnit單元測試中用xUnit.DependencyInject來使用依賴註入,上一章我們的Sample.Repository倉儲層有一個批量註入的介面沒有做單元測試,今天用這個示例來演示一下如何用Bogus創建模擬數據 ,和 EFCore 的種子數據生成 Bogus 的優 ...
  • 一、前言 在自己的項目中,涉及到實時心率曲線的繪製,項目上的曲線繪製,一般很難找到能直接用的第三方庫,而且有些還是定製化的功能,所以還是自己繪製比較方便。很多人一聽到自己畫就害怕,感覺很難,今天就分享一個完整的實時心率數據繪製心率曲線圖的例子;之前的博客也分享給DrawingVisual繪製曲線的方 ...
  • 如果你在自定義的 Main 方法中直接使用 App 類並啟動應用程式,但發現 App.xaml 中定義的資源沒有被正確載入,那麼問題可能在於如何正確配置 App.xaml 與你的 App 類的交互。 確保 App.xaml 文件中的 x:Class 屬性正確指向你的 App 類。這樣,當你創建 Ap ...
  • 一:背景 1. 講故事 上個月有個朋友在微信上找到我,說他們的軟體在客戶那邊隔幾天就要崩潰一次,一直都沒有找到原因,讓我幫忙看下怎麼回事,確實工控類的軟體環境複雜難搞,朋友手上有一個崩潰的dump,剛好丟給我來分析一下。 二:WinDbg分析 1. 程式為什麼會崩潰 windbg 有一個厲害之處在於 ...
  • 前言 .NET生態中有許多依賴註入容器。在大多數情況下,微軟提供的內置容器在易用性和性能方面都非常優秀。外加ASP.NET Core預設使用內置容器,使用很方便。 但是筆者在使用中一直有一個頭疼的問題:服務工廠無法提供請求的服務類型相關的信息。這在一般情況下並沒有影響,但是內置容器支持註冊開放泛型服 ...
  • 一、前言 在項目開發過程中,DataGrid是經常使用到的一個數據展示控制項,而通常表格的最後一列是作為操作列存在,比如會有編輯、刪除等功能按鈕。但WPF的原始DataGrid中,預設只支持固定左側列,這跟大家習慣性操作列放最後不符,今天就來介紹一種簡單的方式實現固定右側列。(這裡的實現方式參考的大佬 ...