日韩无码专区无码一级三级片|91人人爱网站中日韩无码电影|厨房大战丰满熟妇|AV高清无码在线免费观看|另类AV日韩少妇熟女|中文日本大黄一级黄色片|色情在线视频免费|亚洲成人特黄a片|黄片wwwav色图欧美|欧亚乱色一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
19個JavaScript單行代碼技巧,讓你看起來像個專業(yè)人士

今天這篇文章跟大家分享18個JS單行代碼,你只需花幾分鐘時間,即可幫助您了解一些您可能不知道的 JS 知識,如果您已經(jīng)知道了,就當作復(fù)習一下,古人云,溫故而知新嘛。

現(xiàn)在,我們就開始今天的內(nèi)容。

1. 生成隨機字符串

我們可以使用Math.random來生成一個隨機字符串,當我們需要唯一的ID時,這非常方便。

const randomString = () => Math.random().toString(36).slice(2)
randomString() // gi1qtdego0b
randomString() // f3qixv40mot
randomString() // eeelv1pm3ja

2.轉(zhuǎn)義HTML特殊字符

如果您了解 XSS,解決方案之一就是轉(zhuǎn)義 HTML 字符串。

const escape = (str) => str.replace(/[&<>"']/g, (m) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[m]))
escape('
Hi Medium.
') //
Hi Medium.

3.將字符串中每個單詞的第一個字符大寫

此方法用于將字符串中每個單詞的第一個字符大寫。

const uppercaseWords = (str) => str.replace(/^(.)|\s+(.)/g, (c) => c.toUpperCase())
uppercaseWords('hello world'); // 'Hello World'

謝謝克里斯托弗·斯特羅利亞·戴維斯,以下是他提供的更簡單的方法。

const uppercaseWords = (str) => str.replace(/^(.)|\s+(.)/g, (c) => c.toUpperCase())

4.將字符串轉(zhuǎn)換為駝峰命名法

const toCamelCase = (str) => str.trim().replace(/[-_\s]+(.)?/g, (_, c) => (c ? c.toUpperCase() : ''));
toCamelCase('background-color'); // backgroundColor
toCamelCase('-webkit-scrollbar-thumb'); // WebkitScrollbarThumb
toCamelCase('_hello_world'); // HelloWorld
toCamelCase('hello_world'); // helloWorld

5.刪除數(shù)組中的重復(fù)值

去除數(shù)組的重復(fù)項是非常有必要的,使用“Set”就會變得非常簡單。

const removeDuplicates = (arr) => [...new Set(arr)]
console.log(removeDuplicates([1, 2, 2, 3, 3, 4, 4, 5, 5, 6])) 
// [1, 2, 3, 4, 5, 6]

6.展平數(shù)組

我們經(jīng)常在面試中受到考驗,這可以通過兩種方式來實現(xiàn)。

const flat = (arr) =>
    [].concat.apply(
        [],
        arr.map((a) => (Array.isArray(a) ? flat(a) : a))
    )
// Or
const flat = (arr) => arr.reduce((a, b) => (Array.isArray(b) ? [...a, ...flat(b)] : [...a, b]), [])
flat(['cat', ['lion', 'tiger']]) // ['cat', 'lion', 'tiger']

7.從數(shù)組中刪除假值

使用此方法,您將能夠過濾掉數(shù)組中的所有虛假值。

const removeFalsy = (arr) => arr.filter(Boolean)
removeFalsy([0, 'a string', '', NaN, true, 5, undefined, 'another string', false])
// ['a string', true, 5, 'another string']

8.檢查數(shù)字是偶數(shù)還是奇數(shù)

超級簡單的任務(wù)可以通過使用模運算符 (%) 來解決。

const isEven = num => num % 2 === 0
isEven(2) // true
isEven(1) // false

9.獲取兩個數(shù)字之間的隨機整數(shù)

該方法用于獲取兩個數(shù)字之間的隨機整數(shù)。

const random = (min, max) => Math.floor(Math.random() * (max - min + 1) + min)
random(1, 50) // 25
random(1, 50) // 34

10. 獲取參數(shù)的平均值

我們可以使用reduce方法來獲取我們在此函數(shù)中提供的參數(shù)的平均值。

const average = (...args) => args.reduce((a, b) => a + b) / args.length;
average(1, 2, 3, 4, 5);   // 3

11.將數(shù)字截斷為固定小數(shù)點

使用 Math.pow() 方法,我們可以將數(shù)字截斷到函數(shù)中提供的某個小數(shù)點。

const round = (n, d) => Number(Math.round(n + "e" + d) + "e-" + d)
round(1.005, 2) //1.01
round(1.555, 2) //1.56

12.計算兩個日期相差天數(shù)

有時候我們需要計算兩個日期之間的天數(shù),一行代碼就可以完成。

const diffDays = (date, otherDate) => Math.ceil(Math.abs(date - otherDate) / (1000 * 60 * 60 * 24));
diffDays(new Date("2021-11-3"), new Date("2022-2-1"))  // 90

13.從日期中獲取一年中的第幾天

您想知道某個日期是一年中的第幾天嗎?

const dayOfYear = (date) => Math.floor((date - new Date(date.getFullYear(), 0, 0)) / (1000 * 60 * 60 * 24))
dayOfYear(new Date()) // 74

14.生成隨機的十六進制顏色

如果您需要隨機顏色值,這個函數(shù)就可以了。

const randomColor = () => `#${Math.random().toString(16).slice(2, 8).padEnd(6, '0')}`
randomColor() // #9dae4f
randomColor() // #6ef10e

15.將RGB顏色轉(zhuǎn)換為十六進制

const rgbToHex = (r, g, b) => "#" + ((1 << 24) + (r << 16) + (
g << 8) + b).toString(16).slice(1)
rgbToHex(255, 255, 255)  // '#ffffff'

16.清除所有cookie

const clearCookies = () => document.cookie.split(';').forEach((c) => (document.cookie = c.replace(/^ +/, '').replace(/=.*/, `=;expires=${new Date().toUTCString()};path=/`)))

17.檢測深色模式

const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches

18.交換兩個變量

[foo, bar] = [bar, foo]

19. pause for a while

const pause = (millis) => new Promise(resolve => setTimeout(resolve, millis))
const fn = async () => {
  await pause(1000)
console.log('fatfish') // 1s later
}
fn()

最后

以上就是我今天與你分享的關(guān)于JS的19個一行代碼技巧,希望能夠?qū)δ兴鶐椭?,感謝您的閱讀,祝編程愉快!


本文標題:19個JavaScript單行代碼技巧,讓你看起來像個專業(yè)人士
網(wǎng)頁路徑:http://www.5511xx.com/article/dhdegjp.html