日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 >

30秒就能理解的JavaScript优秀代码

發(fā)布時(shí)間:2025/7/14 61 豆豆
生活随笔 收集整理的這篇文章主要介紹了 30秒就能理解的JavaScript优秀代码 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

數(shù)組

arrayMax

返回?cái)?shù)組中的最大值。

將Math.max()與擴(kuò)展運(yùn)算符 (…) 結(jié)合使用以獲取數(shù)組中的最大值。

const arrayMax = arr => Math.max(...arr); // arrayMax([10, 1, 5]) -> 10

arrayMin

返回?cái)?shù)組中的最小值。

將Math.min()與擴(kuò)展運(yùn)算符 (…) 結(jié)合使用以獲取數(shù)組中的最小值。

const arrayMin = arr => Math.min(...arr); // arrayMin([10, 1, 5]) -> 1

chunk

將數(shù)組塊劃分為指定大小的較小數(shù)組。

使用Array.from()創(chuàng)建新的數(shù)組, 這符合將生成的區(qū)塊數(shù)。使用Array.slice()將新數(shù)組的每個(gè)元素映射到size長度的區(qū)塊。如果原始數(shù)組不能均勻拆分, 則最終的塊將包含剩余的元素。

const chunk = (arr, size) => Array.from({length: Math.ceil(arr.length / size)}, (v, i) => arr.slice(i * size, i * size + size)); // chunk([1,2,3,4,5], 2) -> [[1,2],[3,4],[5]]

compact

從數(shù)組中移除 falsey 值。

使用Array.filter()篩選出 falsey 值 (false、null、0、”“、undefined和NaN).

const compact = (arr) => arr.filter(Boolean); // compact([0, 1, false, 2, '', 3, 'a', 'e'*23, NaN, 's', 34]) -> [ 1, 2, 3, 'a', 's', 34 ]

countOccurrences

計(jì)算數(shù)組中值的出現(xiàn)次數(shù)。

使用Array.reduce()在每次遇到數(shù)組中的特定值時(shí)遞增計(jì)數(shù)器。

const countOccurrences = (arr, value) => arr.reduce((a, v) => v === value ? a + 1 : a + 0, 0); // countOccurrences([1,1,2,1,2,3], 1) -> 3

deepFlatten

深拼合數(shù)組。

使用遞歸。使用Array.concat()與空數(shù)組 ([]) 和跨頁運(yùn)算符 (…) 來拼合數(shù)組。遞歸拼合作為數(shù)組的每個(gè)元素。

const deepFlatten = arr => [].concat(...arr.map(v => Array.isArray(v) ? deepFlatten(v) : v)); // deepFlatten([1,[2],[[3],4],5]) -> [1,2,3,4,5]

difference

返回兩個(gè)數(shù)組之間的差異。

從b創(chuàng)建Set, 然后使用Array.filter() on 只保留a b中不包含的值.

const difference = (a, b) => { const s = new Set(b); return a.filter(x => !s.has(x)); }; // difference([1,2,3], [1,2,4]) -> [3]

distinctValuesOfArray

返回?cái)?shù)組的所有不同值。

使用 ES6 Set和…rest運(yùn)算符放棄所有重復(fù)的值。

const distinctValuesOfArray = arr => [...new Set(arr)]; // distinctValuesOfArray([1,2,2,3,4,4,5]) -> [1,2,3,4,5]

dropElements

移除數(shù)組中的元素, 直到傳遞的函數(shù)返回true。返回?cái)?shù)組中的其余元素。 在數(shù)組中循環(huán), 使用Array.shift()將數(shù)組的第一個(gè)元素除去, 直到函數(shù)的返回值為true。返回其余元素。

const dropElements = (arr, func) => { while (arr.length > 0 && !func(arr[0])) arr.shift(); return arr; }; // dropElements([1, 2, 3, 4], n => n >= 3) -> [3,4]

everyNth

返回?cái)?shù)組中的每個(gè)第 n 個(gè)元素。

使用Array.filter()創(chuàng)建一個(gè)包含給定數(shù)組的每個(gè)第 n 個(gè)元素的新數(shù)組。

const everyNth = (arr, nth) => arr.filter((e, i) => i % nth === 0); // everyNth([1,2,3,4,5,6], 2) -> [ 1, 3, 5 ]

filterNonUnique

篩選出數(shù)組中的非唯一值。

對(duì)于只包含唯一值的數(shù)組, 請(qǐng)使用Array.filter()。

const filterNonUnique = arr => arr.filter(i => arr.indexOf(i) === arr.lastIndexOf(i)); // filterNonUnique([1,2,2,3,4,4,5]) -> [1,3,5]

flatten

拼合數(shù)組。

使用Array.reduce()獲取數(shù)組中的所有元素和concat()以拼合它們。

const flatten = arr => arr.reduce((a, v) => a.concat(v), []); // flatten([1,[2],3,4]) -> [1,2,3,4]

flattenDepth

將數(shù)組向上拼合到指定深度。

使用遞歸, 遞減depth, 每層深度為1。使用Array.reduce()和Array.concat()來合并元素或數(shù)組。基本情況下, 對(duì)于等于1的depth停止遞歸。省略第二個(gè)元素,depth僅拼合到1的深度 (單個(gè)拼合)。

const flattenDepth = (arr, depth = 1) => depth != 1 ? arr.reduce((a, v) => a.concat(Array.isArray(v) ? flattenDepth(v, depth - 1) : v), []) : arr.reduce((a, v) => a.concat(v), []); // flattenDepth([1,[2],[[[3],4],5]], 2) -> [1,2,[3],4,5]

groupby

根據(jù)給定函數(shù)對(duì)數(shù)組元素進(jìn)行分組。

使用Array.map()將數(shù)組的值映射到函數(shù)或?qū)傩悦J褂肁rray.reduce()創(chuàng)建一個(gè)對(duì)象, 其中的鍵是從映射的結(jié)果生成的。

const groupBy = (arr, func) => arr.map(typeof func === 'function' ? func : val => val[func]) .reduce((acc, val, i) => { acc[val] = (acc[val] || []).concat(arr[i]); return acc; }, {}); // groupBy([6.1, 4.2, 6.3], Math.floor) -> {4: [4.2], 6: [6.1, 6.3]} // groupBy(['one', 'two', 'three'], 'length') -> {3: ['one', 'two'], 5: ['three']}

head

返回列表的頭。

使用arr[0]可返回傳遞的數(shù)組的第一個(gè)元素。

const head = arr => arr[0]; // head([1,2,3]) -> 1

initial

返回除最后一個(gè)數(shù)組之外的所有元素。

使用 “arr.slice(0,-1)” 返回?cái)?shù)組的最后一個(gè)元素。

const initial = arr => arr.slice(0, -1); // initial([1,2,3]) -> [1,2]

initializeArrayWithRange

初始化包含指定范圍內(nèi)的數(shù)字的數(shù)組。

使用Array(end-start)創(chuàng)建所需長度的數(shù)組Array.map()以填充區(qū)域中所需的值。可以省略start以使用默認(rèn)值0.

const initializeArrayWithRange = (end, start = 0) => Array.from({ length: end - start }).map((v, i) => i + start); // initializeArrayWithRange(5) -> [0,1,2,3,4]

initializeArrayWithValues

初始化并填充具有指定值的數(shù)組。

使用Array(n)創(chuàng)建所需長度的數(shù)組,fill(v)以填充所需的值。可以省略value以使用默認(rèn)值0.

const initializeArrayWithValues = (n, value = 0) => Array(n).fill(value); // initializeArrayWithValues(5, 2) -> [2,2,2,2,2]

intersection

返回兩個(gè)數(shù)組中存在的元素的列表。

從b創(chuàng)建Set, 然后使用Array.filter()on a只保留b中包含的值.

const intersection = (a, b) => { const s = new Set(b); return a.filter(x => s.has(x)); }; // intersection([1,2,3], [4,3,2]) -> [2,3]

last

返回?cái)?shù)組中的最后一個(gè)元素。

使用arr.length - 1可計(jì)算給定數(shù)組的最后一個(gè)元素的索引并返回它。

const last = arr => arr[arr.length - 1]; // last([1,2,3]) -> 3

mapObject

使用函數(shù)將數(shù)組的值映射到對(duì)象, 其中鍵值對(duì)由原始值作為鍵和映射值組成。

使用匿名內(nèi)部函數(shù)范圍來聲明未定義的內(nèi)存空間, 使用閉包來存儲(chǔ)返回值。使用新的Array可將該數(shù)組與函數(shù)的映射放在其數(shù)據(jù)集上, 而逗號(hào)運(yùn)算符返回第二個(gè)步驟, 而不需要從一個(gè)上下文移動(dòng)到另一個(gè)環(huán)境 (由于關(guān)閉和操作順序)。

const mapObject = (arr, fn) => (a => (a = [arr, arr.map(fn)], a[0].reduce( (acc,val,ind) => (acc[val] = a[1][ind], acc), {}) )) ( ); /* const squareIt = arr => mapObject(arr, a => a*a) squareIt([1,2,3]) // { 1: 1, 2: 4, 3: 9 } */

nthElement

返回?cái)?shù)組的第 n 個(gè)元素。

使用Array.slice()可獲取包含第 n 個(gè)元素的數(shù)組。如果索引超出界限, 則返回[]。省略第二個(gè)參數(shù)n, 以獲取數(shù)組的第一個(gè)元素。

const nthElement = (arr, n=0) => (n>0? arr.slice(n,n+1) : arr.slice(n))[0]; // nthElement(['a','b','c'],1) -> 'b' // nthElement(['a','b','b'],-3) -> 'a'

pick

從對(duì)象中選取對(duì)應(yīng)于給定鍵的鍵值對(duì)。

使用Array.reduce()將篩選/選取的密鑰轉(zhuǎn)換回具有相應(yīng)鍵值對(duì)的對(duì)象 (如果在 obj 中存在該鍵)。

const pick = (obj, arr) => arr.reduce((acc, curr) => (curr in obj && (acc[curr] = obj[curr]), acc), {}); // pick({ 'a': 1, 'b': '2', 'c': 3 }, ['a', 'c']) -> { 'a': 1, 'c': 3 }

pull

對(duì)原始數(shù)組進(jìn)行變異, 以篩選出指定的值。

使用Array.filter()和Array.includes()來拉出不需要的值。使用Array.length = 0可將傳入的數(shù)組中的長度重置為零, 并將其設(shè)置為Array.push(), 以便僅使用所提取的值填充它。

const pull = (arr, ...args) => { let pulled = arr.filter((v, i) => !args.includes(v)); arr.length = 0; pulled.forEach(v => arr.push(v)); }; // let myArray = ['a', 'b', 'c', 'a', 'b', 'c']; // pull(myArray, 'a', 'c'); // console.log(myArray) -> [ 'b', 'b' ]

remove

從數(shù)組中移除給定函數(shù)返回false的元素. 使用Array.filter()查找返回 truthy 值的數(shù)組元素和Array.reduce()以使用Array.splice()刪除元素。使用三參數(shù) (func value, index, array調(diào)用函數(shù)).

const remove = (arr, func) => Array.isArray(arr) ? arr.filter(func).reduce((acc, val) => { arr.splice(arr.indexOf(val), 1); return acc.concat(val); }, []) : []; // remove([1, 2, 3, 4], n => n % 2 == 0) -> [2, 4]

sample

返回?cái)?shù)組中的隨機(jī)元素。

使用Math.random()生成一個(gè)隨機(jī)數(shù), 將它與length相乘, 并使用數(shù)學(xué)將其舍入到最接近的整數(shù)Math.floor()。此方法也適用于字符串。

const sample = arr => arr[Math.floor(Math.random() * arr.length)]; // sample([3, 7, 9, 11]) -> 9

shuffle

隨機(jī)數(shù)組值的順序。

使用Array.sort()可在比較器中使用Math.random()重新排序元素。

const shuffle = arr => arr.sort(() => Math.random() - 0.5); // shuffle([1,2,3]) -> [2,3,1]

similarity

返回兩個(gè)數(shù)組中都顯示的元素的數(shù)組。

使用filter()可刪除不屬于values的值, 使用includes()確定.

const similarity = (arr, values) => arr.filter(v => values.includes(v)); // similarity([1,2,3], [1,2,4]) -> [1,2]

symmetricDifference

返回兩個(gè)數(shù)組之間的對(duì)稱差。

從每個(gè)數(shù)組創(chuàng)建一個(gè)Set, 然后對(duì)它們中的每一個(gè)都使用Array.filter(), 以便只保留其他值中不包含的數(shù)值。

const symmetricDifference = (a, b) => { const sA = new Set(a), sB = new Set(b); return [...a.filter(x => !sB.has(x)), ...b.filter(x => !sA.has(x))]; } // symmetricDifference([1,2,3], [1,2,4]) -> [3,4]

tail

返回?cái)?shù)組中的所有元素, 除第一個(gè)。

如果數(shù)組的length大于1, 則返回arr.slice(1), 否則返回整個(gè)數(shù)組。

const tail = arr => arr.length > 1 ? arr.slice(1) : arr; // tail([1,2,3]) -> [2,3] // tail([1]) -> [1]

take

返回一個(gè)數(shù)組, 其中 n 個(gè)元素從開始處移除。

使用Array.slice()創(chuàng)建數(shù)組的切片, 其中包含從開始處取出的n元素。

const take = (arr, n = 1) => arr.slice(0, n); // take([1, 2, 3], 5) -> [1, 2, 3] // take([1, 2, 3], 0) -> []

takeRight

返回一個(gè)數(shù)組, 其中 n 個(gè)元素從末尾移除。

使用Array.slice()創(chuàng)建數(shù)組的切片, 其中包含從末尾取出的n元素。

const takeRight = (arr, n = 1) => arr.slice(arr.length - n, arr.length); // takeRight([1, 2, 3], 2) -> [ 2, 3 ] // takeRight([1, 2, 3]) -> [3]

union

返回在兩個(gè)數(shù)組中的任意一個(gè)中存在的每個(gè)元素。

創(chuàng)建一個(gè)Set, 其中包含a和b的所有值, 并將其轉(zhuǎn)換為數(shù)組。

const union = (a, b) => Array.from(new Set([...a, ...b])); // union([1,2,3], [4,3,2]) -> [1,2,3,4]

without

篩選出數(shù)組中具有指定值之一的元素。

使用Array.filter()創(chuàng)建不包括的數(shù)組 (使用!Array.includes()) 所有給定值。

const without = (arr, ...args) => arr.filter(v => !args.includes(v)); // without([2, 1, 2, 3], 1, 2) -> [3]

zip

創(chuàng)建基于原始數(shù)組中的位置分組的元素?cái)?shù)組。

使用Math.max.apply()獲取參數(shù)中最長的數(shù)組。創(chuàng)建一個(gè)以該長度為返回值的數(shù)組, 并使用 map 函數(shù)創(chuàng)建一個(gè)分組元素的數(shù)組Array.from()如果參數(shù)數(shù)組的長度不同, 則在未找到任何值的情況下使用undefined。

const zip = (...arrays) => { const maxLength = Math.max(...arrays.map(x => x.length)); return Array.from({length: maxLength}).map((_, i) => { return Array.from({length: arrays.length}, (_, k) => arrays[k][i]); }) } //zip(['a', 'b'], [1, 2], [true, false]); -> [['a', 1, true], ['b', 2, false]] //zip(['a'], [1, 2], [true, false]); -> [['a', 1, true], [undefined, 2, false]]

瀏覽器

bottomVisible

如果頁的底部可見, 則返回true, 否則為false。

使用scrollY、scrollHeight和clientHeight來確定頁面底部是否可見。

const bottomVisible = () => document.documentElement.clientHeight + window.scrollY >= document.documentElement.scrollHeight || document.documentElement.clientHeight; // bottomVisible() -> true

currentURL

返回當(dāng)前 URL。

使用window.location.href獲取當(dāng)前 URL。

const currentURL = () => window.location.href; // currentUrl() -> 'https://google.com'

elementIsVisibleInViewport

如果指定的元素在視區(qū)中可見, 則返回true, 否則為false。

使用Element.getBoundingClientRect()和window.inner(Width|Height)值以確定給定元素在視區(qū)中是否可見。省略第二個(gè)參數(shù)以確定該元素是否完全可見, 或指定true以確定它是否部分可見。

const elementIsVisibleInViewport = (el, partiallyVisible = false) => { const { top, left, bottom, right } = el.getBoundingClientRect(); return partiallyVisible ? ((top > 0 && top < innerHeight) || (bottom > 0 && bottom < innerHeight)) && ((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth)) : top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth; }; // e.g. 100x100 viewport and a 10x10px element at position {top: -1, left: 0, bottom: 9, right: 10} // elementIsVisibleInViewport(el) -> false (not fully visible) // elementIsVisibleInViewport(el, true) -> true (partially visible)

getScrollPosition

返回當(dāng)前頁的滾動(dòng)位置。

如果已定義, 則使用pageXOffset和pageYOffset, 否則scrollLeft和scrollTop。可以省略el以使用window的默認(rèn)值.

const getScrollPosition = (el = window) => ({x: (el.pageXOffset !== undefined) ? el.pageXOffset : el.scrollLeft, y: (el.pageYOffset !== undefined) ? el.pageYOffset : el.scrollTop}); // getScrollPosition() -> {x: 0, y: 200}

getURLParameters

返回一個(gè)包含當(dāng)前 URL 參數(shù)的對(duì)象。

使用match()與適當(dāng)?shù)恼齽t表達(dá)式來獲取所有鍵值對(duì),Array.reduce()可將它們映射并合并到單個(gè)對(duì)象中。將location.search作為要應(yīng)用于當(dāng)前url的參數(shù)傳遞.

const getURLParameters = url => url.match(/([^?=&]+)(=([^&]*))/g).reduce( (a, v) => (a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1), a), {} ); // getURLParameters('http://url.com/page?name=Adam&surname=Smith') -> {name: 'Adam', surname: 'Smith'}

redirect

重定向到指定的 URL。

使用window.location.href或window.location.replace()重定向到url。傳遞第二個(gè)參數(shù)以模擬鏈接單擊 (true-默認(rèn)值) 或 HTTP 重定向 (false).

const redirect = (url, asLink = true) => asLink ? window.location.href = url : window.location.replace(url); // redirect('https://google.com')

scrollToTop

平滑滾動(dòng)到頁面頂部。

使用document.documentElement.scrollTop或document.body.scrollTop從頂部獲取距離。從頂部的距離的一小部分滾動(dòng)。使用window.requestAnimationFrame()對(duì)滾動(dòng)進(jìn)行動(dòng)畫處理。

const scrollToTop = () => { const c = document.documentElement.scrollTop || document.body.scrollTop; if (c > 0) { window.requestAnimationFrame(scrollToTop); window.scrollTo(0, c - c / 8); } }; // scrollToTop()

日期

getDaysDiffBetweenDates

返回兩個(gè)日期之間的差異 (以天為值)。

計(jì)算Date對(duì)象之間的差異 (以天為)。

const getDaysDiffBetweenDates = (dateInitial, dateFinal) => (dateFinal - dateInitial) / (1000 * 3600 * 24); // getDaysDiffBetweenDates(new Date("2017-12-13"), new Date("2017-12-22")) -> 9

JSONToDate

將 JSON 對(duì)象轉(zhuǎn)換為日期。

使用Date(), 將 JSON 格式的日期轉(zhuǎn)換為可讀格式 (dd/mm/yyyy日)).

const JSONToDate = arr => { const dt = new Date(parseInt(arr.toString().substr(6))); return `${ dt.getDate() }/${ dt.getMonth() + 1 }/${ dt.getFullYear() }` }; // JSONToDate(/Date(1489525200000)/) -> "14/3/2017"

toEnglishDate

將日期從美國格式轉(zhuǎn)換為英文格式。

使用Date.toISOString()、split(‘T’)和replace()將日期從美式格式轉(zhuǎn)換為英文格式。如果傳遞的時(shí)間不能轉(zhuǎn)換為日期, 則拋出錯(cuò)誤。

const toEnglishDate = (time) => {try{return new Date(time).toISOString().split('T')[0].replace(/-/g, '/')}catch(e){return}}; // toEnglishDate('09/21/2010') -> '21/09/2010'

功能

chainAsync

鏈異步函數(shù)。

循環(huán)遍歷包含異步事件的函數(shù)數(shù)組, 當(dāng)每個(gè)異步事件完成時(shí)調(diào)用next。

const chainAsync = fns => { let curr = 0; const next = () => fns[curr++](next); next(); }; /* chainAsync([next => { console.log('0 seconds'); setTimeout(next, 1000); },next => { console.log('1 second'); setTimeout(next, 1000); },next => { console.log('2 seconds'); } ])

compose

執(zhí)行從右向左的函數(shù)組合。

使用Array.reduce()執(zhí)行從右向左的函數(shù)組合。最后一個(gè) (最右邊) 的函數(shù)可以接受一個(gè)或多個(gè)參數(shù);其余的函數(shù)必須是一元的。

const compose = (...fns) => fns.reduce((f, g) => (...args) => f(g(...args))); /* const add5 = x => x + 5 const multiply = (x, y) => x * y const multiplyAndAdd5 = compose(add5, multiply) multiplyAndAdd5(5, 2) -> 15 */

curry

Curries a function.

使用遞歸。如果提供的參數(shù) (變量) 的數(shù)量足夠, 請(qǐng)調(diào)用傳遞的函數(shù)args f。否則, 返回需要其余參數(shù)的擴(kuò)充函數(shù)f。如果你想咖喱一個(gè)函數(shù), 接受可變數(shù)目的參數(shù) (如Math.min()), 可以選擇將參數(shù)的個(gè)數(shù)傳遞到第二個(gè)參數(shù)arity(可變函數(shù)).

const curry = (fn, arity = fn.length, ...args) => arity <= args.length ? fn(...args) : curry.bind(null, fn, arity, ...args); // curry(Math.pow)(2)(10) -> 1024 // curry(Math.min, 3)(10)(50)(2) -> 2

functionName

記錄函數(shù)的名稱。

使用console.debug()和傳遞的方法的name屬性將方法的名稱記錄到控制臺(tái)的debug通道中。

const functionName = fn => (console.debug(fn.name), fn); // functionName(Math.max) -> max (logged in debug channel of console)

pipe

執(zhí)行從左向右的函數(shù)組合。

使用Array.reduce()與擴(kuò)展運(yùn)算符 (…) 執(zhí)行從左向右的函數(shù)組合。第一個(gè) (最左邊的) 函數(shù)可以接受一個(gè)或多個(gè)參數(shù);其余的函數(shù)必須是一元的。

const pipeFunctions = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args))); /* const add5 = x => x + 5 const multiply = (x, y) => x * y const multiplyAndAdd5 = pipeFunctions(multiply, add5) multiplyAndAdd5(5, 2) -> 15 */

promisify

轉(zhuǎn)換異步函數(shù)以返回一個(gè)承諾。

使用討好返回一個(gè)返回調(diào)用原始函數(shù)的Promise的函數(shù)。使用…rest運(yùn)算符傳入所有參數(shù)。 在節(jié)點(diǎn) 8 + 中, 可以使用 util.promisify

const promisify = func => (...args) => new Promise((resolve, reject) => func(...args, (err, result) => err ? reject(err) : resolve(result)) ); // const delay = promisify((d, cb) => setTimeout(cb, d)) // delay(2000).then(() => console.log('Hi!')) -> Promise resolves after 2s

runPromisesInSeries

運(yùn)行一系列的承諾系列。

使用Array.reduce()創(chuàng)建一個(gè)承諾鏈, 每個(gè)承諾在解決時(shí)返回下一個(gè)承諾。

const runPromisesInSeries = ps => ps.reduce((p, next) => p.then(next), Promise.resolve()); // const delay = (d) => new Promise(r => setTimeout(r, d)) // runPromisesInSeries([() => delay(1000), () => delay(2000)]) -> executes each promise sequentially, taking a total of 3 seconds to complete

sleep

延遲異步函數(shù)的執(zhí)行。

延遲執(zhí)行async函數(shù)的一部分, 將其放入休眠狀態(tài), 返回Promise.

const sleep = ms => new Promise(resolve => setTimeout(resolve, ms)); /* async function sleepyWork() {console.log('I\'m going to sleep for 1 second.');await sleep(1000);console.log('I woke up after 1 second.'); } */

數(shù)學(xué)

arrayAverage

返回?cái)?shù)字?jǐn)?shù)組的平均值。

使用Array.reduce()將每個(gè)值添加到累加器中, 并以0的值初始化, 除以數(shù)組的length。

const arrayAverage = arr => arr.reduce((acc, val) => acc + val, 0) / arr.length; // arrayAverage([1,2,3]) -> 2

arraySum

返回一個(gè)數(shù)字?jǐn)?shù)組的總和。

使用Array.reduce()將每個(gè)值添加到累加器中, 并以0值初始化.

const arraySum = arr => arr.reduce((acc, val) => acc + val, 0); // arraySum([1,2,3,4]) -> 10

collatz

應(yīng)用 Collatz 算法。

如果n是偶數(shù), 則返回n/2。否則返回3n+1.

const collatz = n => (n % 2 == 0) ? (n / 2) : (3 * n + 1); // collatz(8) --> 4 // collatz(5) --> 16

collatz

將數(shù)字轉(zhuǎn)換為數(shù)字?jǐn)?shù)組。

將數(shù)字轉(zhuǎn)換為字符串, 在 ES6 ([…string]) 中使用擴(kuò)展運(yùn)算符生成數(shù)組。使用Array.map()和parseInt()將每個(gè)值轉(zhuǎn)換為整數(shù)。

const digitize = n => [...''+n].map(i => parseInt(i)); // digitize(2334) -> [2, 3, 3, 4]

digitize

返回兩點(diǎn)之間的距離。

使用Math.hypot()計(jì)算兩個(gè)點(diǎn)之間的歐氏距離。

const distance = (x0, y0, x1, y1) => Math.hypot(x1 - x0, y1 - y0); // distance(1,1, 2,3) -> 2.23606797749979

distance

計(jì)算數(shù)字的階乘。

使用遞歸。如果n小于或等于1, 則返回1。否則, 返回n的乘積和n - 1的階乘。如果n為負(fù)數(shù), 則引發(fā)異常。

const factorial = n => n < 0 ? (() => { throw new TypeError('Negative numbers are not allowed!') })() : n <= 1 ? 1 : n * factorial(n - 1); // factorial(6) -> 720

fibonacci

生成一個(gè)數(shù)組, 包含斐波那契數(shù)列, 直到第 n 個(gè)項(xiàng)。

創(chuàng)建一個(gè)指定長度的空數(shù)組, 初始化前兩個(gè)值 (0和1)。使用Array.reduce()可將值添加到數(shù)組中, 方法是使用前兩個(gè)值的總和, 但前兩個(gè)數(shù)值除外。

const fibonacci = n => Array(n).fill(0).reduce((acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i), []); // fibonacci(5) -> [0,1,1,2,3]

gcd

計(jì)算兩個(gè)數(shù)字之間最大的公共除數(shù)。

使用遞歸。基本情況是當(dāng)y等于0時(shí)。在這種情況下, 返回x。否則, 返回y的 GCD 和除法的其余部分x/y.

const gcd = (x, y) => !y ? x : gcd(y, x % y); // gcd (8, 36) -> 4

hammingDistance

計(jì)算兩個(gè)值之間的漢明距離。

使用 XOR 運(yùn)算符 (^) 可查找兩個(gè)數(shù)字之間的位差, 使用toString(2)轉(zhuǎn)換為二進(jìn)制字符串。使用match(/1/g)計(jì)算并返回字符串中1的數(shù)目。.

const hammingDistance = (num1, num2) => ((num1 ^ num2).toString(2).match(/1/g) || '').length; // hammingDistance(2,3) -> 1

isDivisible

檢查第一個(gè)數(shù)值參數(shù)是否可被另一個(gè)數(shù)字變量整除。

使用模數(shù)運(yùn)算符 (%) 檢查余數(shù)是否等于0.

const isDivisible = (dividend, divisor) => dividend % divisor === 0; // isDivisible(6,3) -> true

iseven

如果給定的數(shù)字為偶數(shù), 則返回true, 否則為false。

檢查一個(gè)數(shù)字是奇數(shù)還是使用模數(shù) (%) 運(yùn)算符。如果數(shù)字為偶數(shù), 則返回true, 如果數(shù)字為奇數(shù), 則為false。

const isEven = num => num % 2 === 0; // isEven(3) -> false

lcm

返回兩個(gè)數(shù)字中最不常見的倍數(shù)。

使用最大的公共除數(shù) (GCD) 公式和Math.abs()來確定最不常見的倍數(shù)。GCD 公式使用遞歸。

const lcm = (x,y) => { const gcd = (x, y) => !y ? x : gcd(y, x % y); return Math.abs(x*y)/(gcd(x,y)); }; // lcm(12,7) -> 84

median

返回?cái)?shù)字?jǐn)?shù)組的中間值。

找到數(shù)組的中間, 使用Array.sort()來對(duì)值進(jìn)行排序。如果length為奇數(shù), 則返回中點(diǎn)的數(shù)字, 否則為兩個(gè)中間數(shù)的平均值。

const median = arr => { const mid = Math.floor(arr.length / 2), nums = arr.sort((a, b) => a - b); return arr.length % 2 !== 0 ? nums[mid] : (nums[mid - 1] + nums[mid]) / 2; }; // median([5,6,50,1,-5]) -> 5 // median([0,10,-2,7]) -> 3.5

palindrome

如果給定字符串為回文, 則返回true, 否則為false。

轉(zhuǎn)換字符串toLowerCase()并使用replace()從其中刪除非字母數(shù)字字符。然后,split(”)到各個(gè)字符,reverse(),join(”), 并將其與原始的、不可逆轉(zhuǎn)的字符串進(jìn)行比較, 然后將其轉(zhuǎn)換為tolowerCase().

const palindrome = str => { const s = str.toLowerCase().replace(/[\W_]/g,''); return s === s.split('').reverse().join(''); } // palindrome('taco cat') -> true

percentile

使用百分比公式計(jì)算給定數(shù)組中有多少個(gè)數(shù)小于或等于給定值。

使用Array.reduce()計(jì)算值的下面有多少, 有多少個(gè)數(shù)是相同的值, 并應(yīng)用百分比公式。

const percentile = (arr, val) => 100 * arr.reduce((acc,v) => acc + (v < val ? 1 : 0) + (v === val ? 0.5 : 0), 0) / arr.length; // percentile([1,2,3,4,5,6,7,8,9,10], 6) -> 55

powerset

返回給定數(shù)字?jǐn)?shù)組的 powerset。

使用Array.reduce()與Array.map()組合, 以循環(huán)訪問元素并將其合并到包含所有組合的數(shù)組中。

const powerset = arr => arr.reduce((a, v) => a.concat(a.map(r => [v].concat(r))), [[]]); // powerset([1,2]) -> [[], [1], [2], [2,1]]

randomIntegerInRange

返回指定范圍內(nèi)的隨機(jī)整數(shù)。

使用Math.random()生成一個(gè)隨機(jī)數(shù)并將其映射到所需的范圍, 使用Math.floor()使其成為整數(shù)。

const randomIntegerInRange = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min; // randomIntegerInRange(0, 5) -> 2

randomNumberInRange

返回指定范圍內(nèi)的隨機(jī)數(shù)。

使用Math.random()生成隨機(jī)值, 并使用乘法將其映射到所需的范圍。

const randomNumberInRange = (min, max) => Math.random() * (max - min) + min; // randomNumberInRange(2,10) -> 6.0211363285087005

round

將數(shù)字四舍五入到指定的位數(shù)。

使用Math.round()和模板文本將數(shù)字舍入到指定的位數(shù)。省略第二個(gè)參數(shù),decimals舍入為整數(shù)。

const round = (n, decimals=0) => Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`); // round(1.005, 2) -> 1.01

standardDeviation

返回?cái)?shù)字?jǐn)?shù)組的標(biāo)準(zhǔn)偏差。

使用Array.reduce()計(jì)算值的平均值、方差和方差的總和, 值的方差, 然后確定標(biāo)準(zhǔn)偏差。可以省略第二個(gè)參數(shù)以獲取樣本標(biāo)準(zhǔn)偏差, 或?qū)⑵湓O(shè)置為true以獲取總體標(biāo)準(zhǔn)偏差。

const standardDeviation = (arr, usePopulation = false) => { const mean = arr.reduce((acc, val) => acc + val, 0) / arr.length; return Math.sqrt( arr.reduce((acc, val) => acc.concat(Math.pow(val - mean, 2)), []) .reduce((acc, val) => acc + val, 0) / (arr.length - (usePopulation ? 0 : 1)) ); }; // standardDeviation([10,2,38,23,38,23,21]) -> 13.284434142114991 (sample) // standardDeviation([10,2,38,23,38,23,21], true) -> 12.29899614287479 (population)

媒體

speechSynthesis

執(zhí)行語音合成 (實(shí)驗(yàn))。

使用SpeechSynthesisUtterance.voice和window.speechSynthesis.getVoices()將郵件轉(zhuǎn)換為語音。使用window.speechSynthesis.speak()播放該消息。了解有關(guān)Web 語音 API 的 SpeechSynthesisUtterance 接口的詳細(xì)信息.

const speechSynthesis = message => { const msg = new SpeechSynthesisUtterance(message); msg.voice = window.speechSynthesis.getVoices()[0]; window.speechSynthesis.speak(msg); }; // speechSynthesis('Hello, World') -> plays the message

節(jié)點(diǎn)

JSONToFile

將 JSON 對(duì)象寫入文件。

使用fs.writeFile()、模板文本和JSON.stringify()將json對(duì)象寫入.json文件。

const fs = require('fs'); const JSONToFile = (obj, filename) => fs.writeFile(`${filename}.json`, JSON.stringify(obj, null, 2)) // JSONToFile({test: "is passed"}, 'testJsonFile') -> writes the object to 'testJsonFile.json'

readFileLines

返回指定文件中的行的數(shù)組。

在fs節(jié)點(diǎn)包中使用readFileSync函數(shù)可以從文件創(chuàng)建Buffer。使用toString(encoding)函數(shù)將緩沖區(qū)轉(zhuǎn)換為字符串。通過spliting 文件內(nèi)容行從文件內(nèi)容創(chuàng)建數(shù)組 (每個(gè)\n).

const fs = require('fs'); const readFileLines = filename => fs.readFileSync(filename).toString('UTF8').split('\n'); /* contents of test.txt :line1line2line3___________________________ let arr = readFileLines('test.txt') console.log(arr) // -> ['line1', 'line2', 'line3'] */

對(duì)象

cleanObj

移除從 JSON 對(duì)象指定的屬性之外的任何特性。

使用Object.keys()方法可以遍歷給定的 json 對(duì)象并刪除在給定數(shù)組中不是included 的鍵。另外, 如果給它一個(gè)特殊的鍵 (childIndicator), 它將在里面深入搜索, 并將函數(shù)應(yīng)用于內(nèi)部對(duì)象。

const cleanObj = (obj, keysToKeep = [], childIndicator) => { Object.keys(obj).forEach(key => { if (key === childIndicator) { cleanObj(obj[key], keysToKeep, childIndicator); } else if (!keysToKeep.includes(key)) { delete obj[key]; } }) } /*const testObj = {a: 1, b: 2, children: {a: 1, b: 2}}cleanObj(testObj, ["a"],"children")console.log(testObj)// { a: 1, children : { a: 1}} */

objectFromPairs

從給定的鍵值對(duì)創(chuàng)建對(duì)象。

使用Array.reduce()創(chuàng)建和組合鍵值對(duì)。

const objectFromPairs = arr => arr.reduce((a, v) => (a[v[0]] = v[1], a), {}); // objectFromPairs([['a',1],['b',2]]) -> {a: 1, b: 2}

objectToPairs

從對(duì)象創(chuàng)建鍵值對(duì)數(shù)組的數(shù)組。

使用Object.keys()和Array.map()循環(huán)訪問對(duì)象的鍵并生成具有鍵值對(duì)的數(shù)組。

const objectToPairs = obj => Object.keys(obj).map(k => [k, obj[k]]); // objectToPairs({a: 1, b: 2}) -> [['a',1],['b',2]])

shallowClone

創(chuàng)建對(duì)象的淺表克隆。

使用Object.assign()和一個(gè)空對(duì)象 ({}) 創(chuàng)建原始的淺克隆。

const shallowClone = obj => Object.assign({}, obj); /* const a = { x: true, y: 1 }; const b = shallowClone(a); a === b -> false */

truthCheckCollection

檢查謂詞 (第二個(gè)參數(shù)) 是否 truthy 集合的所有元素 (第一個(gè)參數(shù))。

使用Array.every()檢查每個(gè)傳遞的對(duì)象是否具有指定的屬性, 以及是否返回 truthy 值。

truthCheckCollection = (collection, pre) => (collection.every(obj => obj[pre])); // truthCheckCollection([{"user": "Tinky-Winky", "sex": "male"}, {"user": "Dipsy", "sex": "male"}], "sex") -> true

字符串

anagrams

生成字符串的所有字謎 (包含重復(fù)項(xiàng))。

使用遞歸。對(duì)于給定字符串中的每個(gè)字母, 為其其余字母創(chuàng)建所有部分字謎。使用Array.map()將字母與每個(gè)部分變位詞組合在一起, 然后將Array.reduce()組合在一個(gè)數(shù)組中的所有字謎。基本情況為字符串length等于2或1.

const anagrams = str => { if (str.length <= 2) return str.length === 2 ? [str, str[1] + str[0]] : [str]; return str.split('').reduce((acc, letter, i) => acc.concat(anagrams(str.slice(0, i) + str.slice(i + 1)).map(val => letter + val)), []); }; // anagrams('abc') -> ['abc','acb','bac','bca','cab','cba']

Capitalize

將字符串的第一個(gè)字母大寫。

使用 destructuring 和toUpperCase()可將第一個(gè)字母、…rest用于獲取第一個(gè)字母之后的字符數(shù)組, 然后是Array.join(”)以使其成為字符串。省略lowerRest參數(shù)以保持字符串的其余部分不變, 或?qū)⑵湓O(shè)置為true以轉(zhuǎn)換為小寫。

const capitalize = ([first,...rest], lowerRest = false) => first.toUpperCase() + (lowerRest ? rest.join('').toLowerCase() : rest.join('')); // capitalize('myName') -> 'MyName' // capitalize('myName', true) -> 'Myname'

capitalizeEveryWord

將字符串中每個(gè)單詞的首字母大寫。

使用replace()匹配每個(gè)單詞和toUpperCase()的第一個(gè)字符以將其大寫。

const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperCase()); // capitalizeEveryWord('hello world!') -> 'Hello World!'

escapeRegExp

轉(zhuǎn)義要在正則表達(dá)式中使用的字符串。

使用replace()可轉(zhuǎn)義特殊字符。

const escapeRegExp = str => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // escapeRegExp('(test)') -> \\(test\\)

fromCamelCase

從匹配轉(zhuǎn)換字符串。

使用replace()可刪除下劃線、連字符和空格, 并將單詞轉(zhuǎn)換為匹配。省略第二個(gè)參數(shù)以使用默認(rèn)分隔符_.

const fromCamelCase = (str, separator = '_') => str.replace(/([a-z\d])([A-Z])/g, '$1' + separator + '$2') .replace(/([A-Z]+)([A-Z][a-z\d]+)/g, '$1' + separator + '$2').toLowerCase(); // fromCamelCase('someDatabaseFieldName', ' ') -> 'some database field name' // fromCamelCase('someLabelThatNeedsToBeCamelized', '-') -> 'some-label-that-needs-to-be-camelized' // fromCamelCase('someJavascriptProperty', '_') -> 'some_javascript_property'

reverseString

反轉(zhuǎn)字符串。

使用數(shù)組 destructuring 和Array.reverse()可反轉(zhuǎn)字符串中字符的順序。使用join(”)組合字符以獲取字符串.

const reverseString = str => [...str].reverse().join(''); // reverseString('foobar') -> 'raboof'

sortCharactersInString

按字母順序?qū)ψ址械淖址M(jìn)行排序。

使用split(”)、Array.sort()利用localeCompare()重新組合使用join(”).

const sortCharactersInString = str => str.split('').sort((a, b) => a.localeCompare(b)).join(''); // sortCharactersInString('cabbage') -> 'aabbceg'

toCamelCase

將字符串轉(zhuǎn)換為匹配。

使用replace()可刪除下劃線、連字符和空格, 并將單詞轉(zhuǎn)換為匹配。

const toCamelCase = str => str.replace(/^([A-Z])|[\s-_]+(\w)/g, (match, p1, p2, offset) => p2 ? p2.toUpperCase() : p1.toLowerCase()); // toCamelCase("some_database_field_name") -> 'someDatabaseFieldName' // toCamelCase("Some label that needs to be camelized") -> 'someLabelThatNeedsToBeCamelized' // toCamelCase("some-javascript-property") -> 'someJavascriptProperty' // toCamelCase("some-mixed_string with spaces_underscores-and-hyphens") -> 'someMixedStringWithSpacesUnderscoresAndHyphens'

truncateString

將字符串截?cái)酁橹付ㄩL度。

確定字符串的length是否大于num。將截?cái)嗟淖址祷氐剿璧拈L度, 并將…追加到末尾或原始字符串。

const truncateString = (str, num) => str.length > num ? str.slice(0, num > 3 ? num - 3 : num) + '...' : str; // truncateString('boomerang', 7) -> 'boom...'

實(shí)用

coalesce

返回第一個(gè)非空/未定義參數(shù)。

使用Array.find()返回第一個(gè)非null/undefined的參數(shù)。

const coalesce = (...args) => args.find(_ => ![undefined, null].includes(_)) // coalesce(null,undefined,"",NaN, "Waldo") -> ""

coalesceFactory

返回自定義的聯(lián)合函數(shù), 返回從提供的參數(shù)驗(yàn)證函數(shù)返回true的第一個(gè)參數(shù)。

使用Array.find()返回從提供的參數(shù)驗(yàn)證函數(shù)返回true的第一個(gè)參數(shù)。

const coalesceFactory = valid => (...args) => args.find(valid); // const customCoalesce = coalesceFactory(_ => ![null, undefined, "", NaN].includes(_)) // customCoalesce(undefined, null, NaN, "", "Waldo") //-> "Waldo"

extendHex

將3位色碼擴(kuò)展為6位色碼。

使用Array.map()、split()和Array.join()來加入映射數(shù)組, 將3位的 RGB notated 十六進(jìn)制 color-code 轉(zhuǎn)換為6位數(shù)字形式。Array.slice()用于從字符串啟動(dòng)中刪除#, 因?yàn)樗砑恿艘淮巍?/p> const extendHex = shortHex => '#' + shortHex.slice(shortHex.startsWith('#') ? 1 : 0).split('').map(x => x+x).join('') // extendHex('#03f') -> '#0033ff' // extendHex('05a') -> '#0055aa'

gettype

返回值的本機(jī)類型。

如果值未定義或?yàn)?null, 則返回小寫的構(gòu)造函數(shù)名稱、”未定義” 或 “null”

const getType = v => v === undefined ? 'undefined' : v === null ? 'null' : v.constructor.name.toLowerCase(); // getType(new Set([1,2,3])) -> "set"

hexToRGB

將 colorcode 轉(zhuǎn)換為rgb()字符串。

使用按位右運(yùn)算符和掩碼位與&(and) 運(yùn)算符將十六進(jìn)制顏色代碼 (前綴為#) 轉(zhuǎn)換為具有 RGB 值的字符串。如果它是一個(gè)3位數(shù)的 colorcode, 那么用 extendHex () 函數(shù) (ref.extendHex代碼段) 擴(kuò)展的6位 colorcode 進(jìn)行相同的處理

const hexToRgb = hex => { const extendHex = shortHex => '#' + shortHex.slice(shortHex.startsWith('#') ? 1 : 0).split('').map(x => x+x).join(''); const extendedHex = hex.slice(hex.startsWith('#') ? 1 : 0).length === 3 ? extendHex(hex) : hex; return `rgb(${parseInt(extendedHex.slice(1), 16) >> 16}, ${(parseInt(extendedHex.slice(1), 16) & 0x00ff00) >> 8}, ${parseInt(extendedHex.slice(1), 16) & 0x0000ff})`; } // hexToRgb('#27ae60') -> 'rgb(39, 174, 96)' // hexToRgb('#acd') -> 'rgb(170, 204, 221)'

isArray

檢查給定參數(shù)是否為數(shù)組。

使用Array.isArray()檢查某個(gè)值是否屬于數(shù)組。

const isArray = val => !!val && Array.isArray(val); // isArray(null) -> false // isArray([1]) -> true

isBoolean

檢查給定的參數(shù)是否為本機(jī)布爾元素。

使用typeof檢查某個(gè)值是否被歸類為布爾基元。

const isBoolean = val => typeof val === 'boolean'; // isBoolean(null) -> false // isBoolean(false) -> true

isFunction

檢查給定參數(shù)是否為函數(shù)。

使用typeof檢查某個(gè)值是否被歸類為函數(shù)基元。

const isFunction = val => val && typeof val === 'function'; // isFunction('x') -> false // isFunction(x => x) -> true

isNumber

檢查給定參數(shù)是否為數(shù)字。

使用typeof檢查某個(gè)值是否歸類為數(shù)字基元。

const isNumber = val => typeof val === 'number'; // isNumber('1') -> false // isNumber(1) -> true

isString

檢查給定參數(shù)是否為字符串。

使用typeof檢查某個(gè)值是否屬于字符串基元。

const isString = val => typeof val === 'string'; // isString(10) -> false // isString('10') -> true

isSymbol

檢查給定參數(shù)是否為符號(hào)。

使用typeof檢查某個(gè)值是否被歸類為符號(hào)基元。

const isSymbol = val => typeof val === 'symbol'; // isSymbol('x') -> false // isSymbol(Symbol('x')) -> true

RGBToHex

將 RGB 組件的值轉(zhuǎn)換為 colorcode。

使用按位左移位運(yùn)算符 (<<) 和toString(16)將給定的 RGB 參數(shù)轉(zhuǎn)換為十六進(jìn)制字符串, 然后padStart(6,’0’)以獲取6位十六進(jìn)制值。

const RGBToHex = (r, g, b) => ((r << 16) + (g << 8) + b).toString(16).padStart(6, '0'); // RGBToHex(255, 165, 1) -> 'ffa501'

timeTaken

測(cè)量執(zhí)行函數(shù)所用的時(shí)間。

使用console.time()和console.timeEnd()來測(cè)量開始和結(jié)束時(shí)間之間的差異, 以確定回調(diào)執(zhí)行所用的時(shí)間。

const timeTaken = callback => { console.time('timeTaken'); const r = callback(); console.timeEnd('timeTaken'); return r; }; // timeTaken(() => Math.pow(2, 10)) -> 1024 // (logged): timeTaken: 0.02099609375ms

toOrdinalSuffix

將序號(hào)后綴添加到數(shù)字。

使用模數(shù)運(yùn)算符 (%) 查找單個(gè)和十位數(shù)字的值。查找匹配的序號(hào)模式數(shù)字。如果在青少年模式中發(fā)現(xiàn)數(shù)字, 請(qǐng)使用青少年序號(hào)。

const toOrdinalSuffix = num => { const int = parseInt(num), digits = [(int % 10), (int % 100)], ordinals = ['st', 'nd', 'rd', 'th'], oPattern = [1, 2, 3, 4], tPattern = [11, 12, 13, 14, 15, 16, 17, 18, 19]; return oPattern.includes(digits[0]) && !tPattern.includes(digits[1]) ? int + ordinals[digits[0] - 1] : int + ordinals[3]; }; // toOrdinalSuffix("123") -> "123rd"

UUIDGenerator

生成 UUID。

使用cryptoAPI 生成 UUID, 符合RFC4122版本4。

const UUIDGenerator = () => ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c => (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16) ); // UUIDGenerator() -> '7982fcfe-5721-4632-bede-6000885be57d'

validateEmail

如果給定的字符串是有效的電子郵件, 則返回true, 否則為false。

使用正則表達(dá)式檢查電子郵件是否有效。如果電子郵件有效, 則返回 true, 如果沒有, 則返回false。

const validateEmail = str =>/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(str); // validateEmail(mymail@gmail.com) -> true

validateNumber

如果給定值為數(shù)字, 則返回true, 否則為false。

將!isNaN與parseFloat()結(jié)合使用, 以檢查參數(shù)是否為數(shù)字。使用isFinite()檢查數(shù)字是否是有限的。使用Number()檢查強(qiáng)制是否保持。

const validateNumber = n => !isNaN(parseFloat(n)) && isFinite(n) && Number(n) == n; // validateNumber('10') -> true

感謝作者分享了大量有用的Javascript片段,本文為中文版翻譯,下面一起來看看有哪些精彩的JavaScript代碼值得收藏。

原文:https://github.com/Chalarangelo/30-seconds-of-code

作者:Chalarangelo

翻譯:http://caibaojian.com/30-seconds-of-code.html

譯者:蔡寶堅(jiān)

本文翻譯為前端開發(fā)博客所有,如有需要轉(zhuǎn)載,請(qǐng)?jiān)敿?xì)注明以上信息。

總結(jié)

以上是生活随笔為你收集整理的30秒就能理解的JavaScript优秀代码的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。