JavaScript中簡單而有效的用法

數組去重

使用ES6中提供的Set數據結構

const arr = [1, 2, 3, 4, 3, 2, 1]
const newArr = [...new Set(arr)]
// 或
const newArr = Array.from(new Set(arr))

console.log(newArr)

使用數組中的reduce方法

const arr = [1, 2, 3, 4, 3, 2, 1]

const newArr = arr.reduce((result, item) => {
  if (!result.includes(item)) {
    result.push(item)
  }
  return result
}, [])

console.log(newArr)

變量交換

假設如今有a,b兩個變量,在不依賴於臨時變量的狀況下,如何快速的實現變量之間的值交換呢?css

解構賦值

let a = 1
let b = 2
[a, b] = [b, a]

console.log(a, b) // a --> 2, b --> 1

位異或

let a = 1
let b = 2

// 使用位異或運算
a = a ^ b
b = b ^ a
a = a ^ b

// 或直接交換
a = a + b
b = a - b
a = a - b

console.log(a, b) // a --> 2, b --> 1

借用數組

let a = 1
let b = 2

b = [a, a = b][0]

console.log(a, b) // a --> 2, b --> 1

字符串分組

將字符轉以特定的字符進行分組, 好比按照空格,逗號,分號字符進行分組前端

const str = 'a b,c;d,e f,cf'

const result = str.match(/[^\s,;]+/g)

// result -> ["a", "b", "c", "d", "e", "f", "cf"]

隨機字符串

利用Math.random()生成隨機數字,而後再經過tostring方法將其轉換爲隨機字符串api

const str = Math.random().toString(36).substr(2)

console.log(str) // --> "3mknchm44dt"

密碼強度判斷

判斷規則:數組

  • 長度必須大於6
  • 包含數字,密碼強度+1
  • 包含大/小寫字母,密碼強度+1
  • 包含除數字和大小寫字母外的其餘字符,密碼強度+1
function getStrength(str) {
  let strength = 0
  if (str && str.length >= 6) {
    if (/\d+/.test(str)) {
      ++strength
    }
    if (/[a-zA-Z]+/.test(str)) {
      ++strength
    }
    if (/[^0-9a-zA-Z]+/.test(str)) {
      ++strength
    }
  }

  return strength
}

首字母大寫

使用CSS

.text {
  text-transform: capitalize;
}

使用JS

const upperCase = data => {
  if (data) {
    const [first, ...char] = data

    return first.toUpperCase() + char.join('')
  }

  return ''
}

console.log(upperCase('hello'))

這裏用到了字符串的解構賦值,即將第一個字母賦值給first,其他字母賦值到char中,從而實現將首字母轉換爲大寫。promise

鏈判斷運算符

在開發中,若是須要讀取對象內部的某個屬性,每每須要判斷該對象是否存在。好比,須要獲取result.userInfo.username中的username,爲了不js報錯,通常的寫法爲:瀏覽器

const { username } = result.userInfo || {}
// 或
const username = result.userInfo ? result.userInfo.username : ''

這樣,每一層對象的屬性都必須判斷是否存在,對象層級關係較大,則寫法更加複雜。好在ES2020 爲咱們提供了鏈判斷運算符(?.),上述的代碼能夠簡化爲服務器

const username = result?.userInfo?.username
// 等同於
const username = result && result.userInfo ? result.userInfo.username : undefined

const name = form.querySelector('input')?.value
// 等同於
const name = form.querySelector('input') ? form.querySelector('input').value : undefined

鏈判斷運算符也能夠判斷方法是否存在微信

actions?.getuserInfo?.()
// 等同於
actions && actions.getUserInfo ? actions.getUserInfo() : undefined

可是,在現代瀏覽器中,還不支持這種寫法,因此咱們必須藉助babel將它轉義爲現代瀏覽器可識別的代碼。babel

  • 安裝依賴 yarn add -D @babel/plugin-proposal-optional-chaining
  • 在.babelrc中進行配置
{
  "presets": ["@babel/preset-env"],
  "plugins": [
    "@babel/plugin-proposal-optional-chaining"
  ]
}

接下來就能夠愉快的使用鏈判斷運算符啦!網絡

複製內容到剪切板

複製任何內容到剪切板,並返回一個promise

function setStyle (el, styleName, value) {
  if (el && styleName) {
    if (typeof styleName == 'object') {
      for (let key in styleName) {
        setStyle(el, key, styleName[key])
      }
    } else {
      el.style[styleName] = value
    }
  }
}

function copyText(value) {
  return new Promise((resolve, reject) => {
    const el = document.createElement('input')

    el.setAttribute('readonly', 'readonly')
    setStyle(el, {
      fontSize: '12px',
      border: 0,
      outline: 0,
      margin: 0,
      padding: 0,
      position: 'fixed',
      top: 0,
      left: '-9999px',
      zIndex: -10
    })
    el.value = value
    document.body.appendChild(el)
    el.select()
    el.setSelectionRange(0, String(value).length)

    if (document.execCommand('Copy')) {
      resolve(value)
    } else {
      reject(new Error('Copy failed'))
    }

    setTimeout(() => {
      el.remove()
    }, 3000)
  })
}

copyText('hello world')
  .then(() => console.log('success'))
  .catch(e =>  console.log(e.message))

防抖和節流

防抖

概念:防抖的做用在於,若是某個事件或函數在某個時間段內連續觸發,那麼只有最後一次觸發,事件回調或函數纔會被真正的調用。如瀏覽器的resize, scroll, mousemove等事件。在短期內會被屢次觸發,若是不加以限制,不只浪費客戶端資源,還有可能形成客戶端卡頓,卡死以及崩潰。若是有網絡請求,短期內大量的網絡請求還會形成網絡堵塞(因爲瀏覽器的限制,通常瀏覽器只能同時處理6個左右的請求,當請求過多時,只有等請求隊列中的請求都完成後,纔會開始下一個請求,不然排隊中的請求一直處於等待狀態,沒法被處理)以及增長服務器壓力。

function debounce(fn, timeout = 500) {
  // 這裏經過閉包使timer變量不會被JS垃圾回收機制回收,從而常駐內存中
  let timer = null

  return function(...args) {
    if (!timer) {
      timer = setTimeout(() => {
        fn.apply(this, args)
        timer = null
      }, timeout)
    }
  }
}

// 這裏將函數經過節流函數封裝後返回`fn`
const fn = debounce(() => console.log('debounce'))

節流

概念:顧名思義,節流的意義在於限制其流入/流出量。一般用在當一個事件或函數在某個時間內連續觸發或調用時,在必定時間段內,只調用一次事件處理函數。如某個事件在特定的狀況下,20秒內觸發了50次,每次都會向服務器發送數據請求,經過節流限制其執行次數,即1s內只容許其執行1次,這樣大大的減小了請求數量,減輕服務器壓力的同時,也減小了客戶端的內存開銷,避免了出現內存泄漏。

function throttle(fn, delay = 1000) {
  let last = 0

  return function(...args) {
    const current = Date.now()
    if (current - last > delay) {
      fn.apply(this, args)
      last = current
    }
  }
}

一言以蔽之,防抖函數的做用在於在特定時間內連續觸發的事件,只有最後一次會被執行。節流函數的做用在於,在固定時間內連續被觸發的事件在n秒內只能被觸發執行一次。


及時獲取更新,瞭解更多動態,請關注 https://www.gogoing.site

若是你以爲這篇文章對你有幫助,歡迎關注微信公衆號-前端學堂,更多精彩文章等着你!

相關文章
相關標籤/搜索