常用的JavaScript代码片段

Published on

zoom-img

列举一下前端开发中常用的 JavaScript 代码片段,方便今后复习查阅。

1. 三元表达式

但是,不要过度使用它。它会使你的代码更加冗长。明智的做法是仅用此替换简单的表达式以提高可读性并减少代码行数。

const age = 12
let ageGroup

// LONG FORM
if (age > 18) {
  ageGroup = 'An adult'
} else {
  ageGroup = 'A child'
}

// SHORTHAND
ageGroup = age > 18 ? 'An adult' : 'A child'

2. 空值合并

空值合并运算符(??)是一个逻辑运算符,当左侧的操作数为 null 或者 undefined 时,返回其右侧操作数,否则返回左侧操作数。

let something

// LONG FORM
if (something) {
  console.log(something)
} else {
  console.log('Nothing found')
}

// SHORTHAND
console.log(something ?? 'Nothing found')

3.数组去重

const uniqueArray = (array) => [...new Set(array)]
uniqueArray([1, 1, 2, 2, 3, 3]) // [1,2,3]

4. 将任何值转换为布尔值

!!true // true
!!2 // true
!![] // ture
!!'Test' // true

!!false // false
!!0 // false
!!'' // false

5. 扩展运算符

// 组合数组
const nums1 = [1, 2, 3]
const nums2 = [4, 5, 6]
// LONG FORM
let newArray = nums1.concat(nums2)
// SHORTHAND
newArray = [...nums1, ...nums2]

// 推送数组
let numbers = [1, 2, 3]
// LONG FORM
numbers.push(4)
// SHORTHAND
numbers = [...numbers, 4, 5]

6. 返回当前访问的 URL 地址

const currentURL = () => window.location.href
currentURL() // 'https://www.baidu.com/'

7. 生成随机数

const random = (min, max) => Math.floor(Math.random() * (max - min)) + min

random(10, 14) // [10, 11, 12, 13]

此随机函数包括下限,但不包括上限。

8. 生成指定范围的 number 数组

const range = (start, end, step = 1) => {
  let output = []

  if (end === undefined) {
    end = start
    start = 0
  }

  for (let i = start; i < end; i += step) {
    output.push(i)
  }
  return output
}

range(5) // [0, 1, 2, 3, 4]

range(5, 10) // [5, 6, 7, 8, 9]

range(0, 6, 2) // [0, 2, 4]

9. 函数防抖

const debounce = (callback, wait) => {
  let timeoutId = null

  return (...args) => {
    window.clearTimeout(timeoutId)

    timeoutId = window.setTimeout(() => {
      callback.apply(null, args)
    }, wait)
  }
}
// 示例
const handleMouseMove = debouce((ev) => {
  // Do stuff with the event!
}, 250)

window.addEventListener('mousemove', handleMouseMove)

在此示例中,在用户开始移动鼠标,然后停止移动鼠标至少 250 毫秒之前,不会发生任何操作。

10. 函数节流

const throttle = (callback, wait) => {
  let timeoutId = null

  return (...arg) => {
    if (!timeoutId) {
      timeoutId = setTimeout(() => {
        timeoutId = null
        callback.apply(null, arg)
      }, wait)
    }
  }
}
// 示例
const handleOnScroll = throttle((ev) => {
  // Do stuff with the event!
}, 250)

window.addEventListener('onScroll', handleOnScroll)

在此示例中,在用户开始滚动滑轮,然后间隔 250 毫秒执行一次操作。

以上就是本文的全部内容,感谢阅读。