工作中經常用到的 8 個Javascript方法,記住并收藏這些方法,避免重新發明輪子。
回到頂部
當頁面很長時,如果使用者想回到頁面頂部,必須滾動滾動鍵幾次才能回到頂部。如果頁面右下角有“傳回頂部”按鈕,使用者可以點選傳回頂部。對于使用者來說,這是一個很好的使用者體驗。
// Method 1
constbindTop1 = () => {
window.scrollTo(0, 0)
document.documentElement.scrollTop = 0;
}
// Method 2: Scrolling through the timer will be visually smoother, without much lag effect
constbindTop2 = () => {
const timeTop = setInterval(() => {
document.documentElement.scrollTop = scrollTopH.value -= 50
if (scrollTopH.value <= 0) {
clearInterval(timeTop)
}
}, 10)
}
将文本複制到剪貼闆
建構網站時一個非常普遍的需求是能夠通過單擊按鈕将文本複制到剪貼闆。以下這段代碼是一個很通用的代碼,适合大多數浏覽器。
const copyText = (text) => {
const clipboardStr = window.clipboardStr
if (clipboardStr) {
clipboardStr.clearData()
clipboardStr.setData('Text', text)
return true
} else if (document.execCommand) {
//Note: document, execCommand is deprecated but some browsers still support it. Remember to check the compatibility when using it
// Get the content to be copied by creating a dom element
const el = document.createElement('textarea')
el.value = text
el.setAttribute('readonly', '')
el.style.position = 'absolute'
el.style.left = '-9999px'
document.body.appendChild(el)
el.select()
// Copy the current content to the clipboard
document.execCommand('copy')
// delete el node
document.body.removeChild(el)
return true
}
return false
}
防抖/節流
在前端開發的過程中,我們會遇到很多按鈕被頻繁點選,然後觸發多個事件,但是我們又不想觸發事件太頻繁。這裡有兩種常見的解決方案來防止 Debouncing 和 Throttling。
基本介紹
防抖:在指定時間内頻繁觸發事件,以最後一次觸發為準。
節流:一個事件在指定時間内被頻繁觸發,并且隻會被觸發一次,以第一次為準。
應用場景
防抖: 輸入搜尋,當使用者不斷輸入内容時,使用防抖來減少請求次數,節省請求資源。
節流:場景一般是按鈕點選。一秒内點選 10 次将發起 10 個請求。節流後,1秒内點選多次,隻會觸發一次。
// Debouncing
// fn is the function that needs anti-shake, delay is the timer time
function debounce(fn,delay){
let timer = null;
return function () {
//if the timer exists, clear the timer and restart the timer
if(timer){
clearTimeout(timeout);
}
//Set a timer and execute the actual function to be executed after a specified time
timeout = setTimeout(() => {
fn.apply(this);
}, delay);
}
}
// Throttling
function throttle(fn) {
let timer = null; // First set a variable, when the timer is not executed, the default is null
return function () {
if (timer) return; // When the timer is not executed, the timer is always false, and there is no need to execute it later
timer = setTimeout(() => {
fn.apply(this, arguments);
// Finally, set the flag to true after setTimeout is executed
// Indicates that the next cycle can be executed.
timer = null;
}, 1000);
};
}
初始化數組
fill() :這是 ES6 中的一個新方法。用指定的元素填充數組,實際上就是用預設的内容初始化數組。
const arrList = Array(6).fill()
console.log(arrList) // result: ['','','','','','']
檢查它是否是一個函數
檢測是否是函數 其實寫完後直接寫isFunction就好了,這樣可以避免重複寫判斷。
const isFunction = (obj) => {
return typeof obj === "function" &&
typeof obj.nodeType !== "number" &&
typeof obj.item !== "function";
檢查它是否是一個安全數組
檢查它是否是一個安全數組,如果不是,用 isArray 方法在這裡傳回一個空數組。
const safeArray = (array) => {
return Array.isArray(array) ? array : []
}
檢查對象是否是安全對象
// Check whether the current object is a valid object.
const isVaildObject = (obj) => {
return typeof obj === 'object' &&
!Array.isArray(obj) && Object.keys(obj).length
}
const safeObject = obj => isVaildObject(obj) ? obj : {}
過濾特殊字元
js中使用正規表達式過濾特殊字元,檢查所有輸入字段是否包含特殊字元。
function filterCharacter(str){
let pattern = new RegExp("[`~!@#$^&*()=:”“'。,、?|{}':;'%,\\[\\].<>/?~!@#¥……&*()&;—|{ }【】‘;]")
let resultStr = "";
for (let i = 0; i < str.length; i++) {
resultStr = resultStr + str.substr(i, 1).replace(pattern, '');
}
return resultStr;
}
filterCharacter('gyaskjdhy12316789#$%^&!@#1=123,./[')
// result: gyaskjdhy123167891123
結束
今天的分享就到這裡,這8個方法你學會了嗎,我強烈建議大家收藏起來,别再造輪子了。希望今天的分享能夠幫助到你,感謝你的閱讀,如果你喜歡我的分享,别忘了點贊轉發,讓更多的人看到,最後别忘記點個關注,你的支援将是我分享最大的動力,後續我會持續輸出更多内容,敬請期待。
原文 :https://levelup.gitconnected.com/8-tools-and-methods-often-used-in-javascript-6fcebaf339ce
作者:Maxwell
非直接翻譯,有自行改編和添加部分。