[]。concat (arr ,... args ); //..." />
<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          精心收集的95個(gè)超實(shí)用的JavaScript代碼片段(ES6 +編寫(xiě))

          共 24885字,需瀏覽 50分鐘

           ·

          2020-09-23 03:39


          Array 數(shù)組

          Array concatenation (數(shù)組拼接)

          使用Array.concat(),通過(guò)在args中附加任何副本和/或值來(lái)拆分一個(gè)數(shù)組。
          JavaScript代碼:
          const ArrayConcat = (arr ,... args )=> []。concat (arr ,... args ); // ArrayConcat([1 ,, [1,2,3,[4]])-> [1,2,3,[4]]

          Array difference (數(shù)組比較)

          根據(jù)副本b創(chuàng)建一個(gè)Set對(duì)象,然后在上方a上使用Array.filter()方法,過(guò)濾出數(shù)組b中不包含的值。
          JavaScript代碼:
          const difference = (a, b) => { const s = new Set(b); return a.filter(x => !s.has(x)); };// difference([1,2,3], [1,2]) -> [3]

          Array includes (數(shù)組包含)

          使用 slice()?來(lái)抵消數(shù)組/字符串,并且使用 indexOf()?來(lái)檢查是否包含該值。如果省略最后一個(gè)參數(shù) fromIndex ,則會(huì)檢查整個(gè)數(shù)組/字符串。
          JavaScript 代碼:
          const includes = (collection, val, fromIndex=0) => collection.slice(fromIndex).indexOf(val) != -1;// includes("30-seconds-of-code", "code") -> true// includes([1, 2, 3, 4], [1, 2], 1) -> false

          Array intersection (數(shù)組交集)

          根據(jù)數(shù)組 b 創(chuàng)建一個(gè) Set 對(duì)象,然后在數(shù)組 a 上使用 Array.filter()?方法,只保留數(shù)組 b 中也包含的值。
          JavaScript 代碼:
          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]

          Array remove (移除數(shù)組中的元素)

          使用 Array.filter()?和 Array.reduce()?來(lái)查找返回真值的數(shù)組元素,使用 Array.splice()?來(lái)移除元素。func 有三個(gè)參數(shù)(value, index, array)。
          JavaScript 代碼:
          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]

          Array sample (數(shù)組取樣隨,機(jī)獲取數(shù)組中的1個(gè)元素)

          使用 Math.random()?生成一個(gè)隨機(jī)數(shù),乘以 length,并使用 Math.floor()?舍去小數(shù)獲得到最接近的整數(shù)。這個(gè)方法也適用于字符串。
          JavaScript 代碼:
          const sample = arr => arr[Math.floor(Math.random() * arr.length)];// sample([3, 7, 9, 11]) -> 9

          Array union (數(shù)組合集)

          用數(shù)組 a 和 b 的所有值創(chuàng)建一個(gè) Set 對(duì)象,并轉(zhuǎn)換成一個(gè)數(shù)組。
          JavaScript 代碼:
          const union = (a, b) => Array.from(new Set([...a, ...b]));// union([1,2,3], [4,3,2]) -> [1,2,3,4]

          Array without (從數(shù)組中排除給定值)

          使用 Array.filter()?創(chuàng)建一個(gè)排除所有給定值的數(shù)組。
          JavaScript 代碼:
          const without = (arr, ...args) => arr.filter(v => args.indexOf(v) === -1);// without([2, 1, 2, 3], 1, 2) -> [3]// without([2, 1, 2, 3, 4, 5, 5, 5, 3, 2, 7, 7], 3, 1, 5, 2) -> [ 4, 7, 7 ]

          Array zip (創(chuàng)建一個(gè)分組元素?cái)?shù)組)

          使用 Math.max.apply()?獲取參數(shù)中最長(zhǎng)的數(shù)組。創(chuàng)建一個(gè)長(zhǎng)度為返回值的數(shù)組,并使用 Array.from()?和 map-function 來(lái)創(chuàng)建一個(gè)分組元素?cái)?shù)組。如果參數(shù)數(shù)組的長(zhǎng)度不同,則在未找到值的情況下使用 undefined 。
          JavaScript 代碼:
          const zip = (...arrays) => { const maxLength = Math.max.apply(null, arrays.map(a => a.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]]

          Average of array of numbers (求數(shù)字?jǐn)?shù)組的平均數(shù))

          使用 Array.reduce()?將數(shù)組中的每個(gè)值添加到一個(gè)累加器,使用?0?初始化,除以數(shù)組的 length (長(zhǎng)度)。
          JavaScript 代碼:
          const average = arr => arr.reduce((acc, val) => acc + val, 0) / arr.length;// average([1,2,3]) -> 2

          Chunk array (數(shù)組分塊)

          使用 Array.from()?創(chuàng)建一個(gè)新的數(shù)組,它的長(zhǎng)度與將要生成的 chunk(塊) 數(shù)量相匹配。使用 Array.slice()?將新數(shù)組的每個(gè)元素映射到長(zhǎng)度為 size 的 chunk 中。如果原始數(shù)組不能均勻分割,最后的 chunk 將包含剩余的元素。
          JavaScript 代碼:
          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 (過(guò)濾掉數(shù)組中所有假值元素)

          使用 Array.filter()?過(guò)濾掉數(shù)組中所有 假值元素(false, null, 0, "", undefined, and NaN)。
          JavaScript 代碼:
          const compact = (arr) => arr.filter(v => v);// compact([0, 1, false, 2, '', 3, 'a', 'e'*23, NaN, 's', 34]) -> [ 1, 2, 3, 'a', 's', 34 ]

          Count occurrences of a value in array (計(jì)數(shù)數(shù)組中某個(gè)值的出現(xiàn)次數(shù))

          每次遇到數(shù)組中的指定值時(shí),使用 Array.reduce()?來(lái)遞增計(jì)數(shù)器。
          JavaScript 代碼:
          const countOccurrences = (arr, value) => arr.reduce((a, v) => v === value ? a + 1 : a + 0, 0);// countOccurrences([1,1,2,1,2,3], 1) -> 3

          Deep flatten array (深度平鋪數(shù)組)

          使用遞歸。通過(guò)空數(shù)組([]) 使用 Array.concat()?,結(jié)合 展開(kāi)運(yùn)算符( ... ) 來(lái)平鋪數(shù)組。遞歸平鋪每個(gè)數(shù)組元素。
          JavaScript 代碼:
          const deepFlatten = arr => [].concat(...arr.map(v => Array.isArray(v) ? deepFlatten(v) : v));// deepFlatten([1,[2],[[3],4],5]) -> [1,2,3,4,5]

          Drop elements in array (刪除數(shù)組中的元素)

          循環(huán)數(shù)組,使用 Array.shift()?刪除數(shù)組的第一個(gè)元素,直到函數(shù)的返回值為 true 。返回其余的元素。
          JavaScript 代碼:
          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]

          Fill array (填充數(shù)組)

          使用 Array.map()?將指定值映射到 start(包含)和 end (排除)之間。省略 start 將從第一個(gè)元素開(kāi)始,省略 end 將在最后一個(gè)元素完成。
          JavaScript 代碼:
          const fillArray = (arr, value, start = 0, end = arr.length) => arr.map((v, i) => i >= start && i < end ? value : v);// fillArray([1,2,3,4],'8',1,3) -> [1,'8','8',4]

          Filter out non-unique values in an array (過(guò)濾出數(shù)組中的非唯一值)

          使用 Array.filter()?濾除掉非唯一值,使數(shù)組僅包含唯一值。
          JavaScript 代碼:
          const filterNonUnique = arr => arr.filter(i => arr.indexOf(i) === arr.lastIndexOf(i));// filterNonUnique([1,2,2,3,4,4,5]) -> [1,3,5]

          Flatten array up to depth (根據(jù)指定的 depth 平鋪數(shù)組)

          每次遞歸,使 depth 減 1 。使用 Array.reduce()?和 Array.concat()?來(lái)合并元素或數(shù)組。默認(rèn)情況下, depth 等于 1 時(shí)停遞歸。省略第二個(gè)參數(shù) depth ,只能平鋪1層的深度 (單層平鋪)。
          JavaScript 代碼:
          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]

          Flatten array (平鋪數(shù)組)

          使用 Array.reduce()?獲取數(shù)組中的所有元素,并使用 concat()?將其平鋪。
          JavaScript 代碼:
          const flatten = arr => arr.reduce((a, v) => a.concat(v), []);// flatten([1,[2],3,4]) -> [1,2,3,4]

          Get max value from array (獲取數(shù)組中的最大值)

          結(jié)合使用 Math.max()?與 展開(kāi)運(yùn)算符( ... ),獲取數(shù)組中的最大值。
          JavaScript 代碼:
          const arrayMax = arr => Math.max(...arr);// arrayMax([10, 1, 5]) -> 10

          Get min value from array (獲取數(shù)組中的最小值)

          結(jié)合使用 Math.max()?與 展開(kāi)運(yùn)算符( ... ),獲取數(shù)組中的最小值。
          JavaScript 代碼:
          const arrayMin = arr => Math.min(...arr);// arrayMin([10, 1, 5]) -> 1

          Group by (數(shù)組分組)

          使用 Array.map()?將數(shù)組的值映射到函數(shù)或?qū)傩悦Q。使用 Array.reduce()?來(lái)創(chuàng)建一個(gè)對(duì)象,其中的 key 是從映射結(jié)果中產(chǎn)生。
          JavaScript 代碼:
          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 of list (獲取數(shù)組的第一個(gè)元素)

          使用 arr[0]?返回傳遞數(shù)組的第一個(gè)元素。
          JavaScript 代碼:
          const head = arr => arr[0];// head([1,2,3]) -> 1

          Initial of list (排除數(shù)組中最后一個(gè)元素)

          使用 arr.slice(0,-1)?返回排除了最后一個(gè)元素的數(shù)組。
          JavaScript 代碼:
          const initial = arr => arr.slice(0, -1);// initial([1,2,3]) -> [1,2]

          Initialize array with range (初始化特定范圍的數(shù)組)

          使用 Array(end-start)?創(chuàng)建所需長(zhǎng)度的數(shù)組,使用 Array.map()?在一個(gè)范圍內(nèi)填充所需的值。
          您可以省略 start ,默認(rèn)值?0。
          JavaScript 代碼:
          const initializeArrayRange = (end, start = 0) => Array.apply(null, Array(end - start)).map((v, i) => i + start);// initializeArrayRange(5) -> [0,1,2,3,4]

          Initialize array with values (初始化特定范圍和值的數(shù)組)

          使用 Array(n)?創(chuàng)建所需長(zhǎng)度的數(shù)組,使用 fill(v)?以填充所需的值。您可以忽略 value ,使用默認(rèn)值?0?。
          JavaScript 代碼:
          const initializeArray = (n, value = 0) => Array(n).fill(value);// initializeArray(5, 2) -> [2,2,2,2,2]

          Last of list (獲取數(shù)組的最后一個(gè)元素)

          使用 arr.slice(-1)[0]?來(lái)獲取給定數(shù)組的最后一個(gè)元素。
          JavaScript 代碼:
          const last = arr => arr.slice(-1)[0];// last([1,2,3]) -> 3

          Median of array of numbers (獲取數(shù)字?jǐn)?shù)組的中值)

          找到數(shù)字?jǐn)?shù)組的中間值,使用 Array.sort()?對(duì)值進(jìn)行排序。如果 length 是奇數(shù),則返回中間值數(shù)字,否則返回兩個(gè)中間值數(shù)值的平均值。
          JavaScript 代碼:
          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

          Nth element of array (獲取數(shù)組的第N個(gè)元素)

          使用 Array.slice()?獲取數(shù)組的第 n 個(gè)元素。如果索引超出范圍,則返回?[]?。省略第二個(gè)參數(shù) n ,將得到數(shù)組的第一個(gè)元素。
          JavaScript 代碼:
          const nth = (arr, n=0) => (n>0? arr.slice(n,n+1) : arr.slice(n))[0];// nth(['a','b','c'],1) -> 'b'// nth(['a','b','b']-2) -> 'a'

          Pick(提取)

          使用 Array.reduce()?只 過(guò)濾/萃取 出 arr 參數(shù)指定 key (如果 key 存在于 obj 中)的屬性值,。
          JavaScript 代碼:
          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 }// pick(object, ['a', 'c'])['a'] -> 1

          Shuffle array (隨機(jī)排列數(shù)組)

          使用 Array.sort()?來(lái)重新排序元素,比較器中使用 Math.random()?。
          JavaScript 代碼:
          const shuffle = arr => arr.sort(() => Math.random() - 0.5);// shuffle([1,2,3]) -> [2,3,1]

          Similarity between arrays (獲取數(shù)組交集)

          使用 filter()?移除不在 values 中的值,使用 includes()?確定。
          JavaScript 代碼:
          const similarity = (arr, values) => arr.filter(v => values.includes(v));// similarity([1,2,3], [1,2,4]) -> [1,2]

          Sum of array of numbers (數(shù)字?jǐn)?shù)組求和)

          使用 Array.reduce()?將每個(gè)值添加到累加器,并使用0值初始化。
          JavaScript 代碼:
          const sum = arr => arr.reduce((acc, val) => acc + val, 0);// sum([1,2,3,4]) -> 10

          Tail of list (返回剔除第一個(gè)元素后的數(shù)組)

          如果數(shù)組的 length 大于 1 ,則返回 arr.slice(1),否則返回整個(gè)數(shù)組。
          JavaScript 代碼:
          const tail = arr => arr.length > 1 ? arr.slice(1) : arr;// tail([1,2,3]) -> [2,3]// tail([1]) -> [1]

          Take right(從一個(gè)給定的數(shù)組中創(chuàng)建一個(gè)后N個(gè)元素的數(shù)組)

          使用 Array.slice()?來(lái)創(chuàng)建一個(gè)從第 n 個(gè)元素開(kāi)始從末尾的數(shù)組。
          JavaScript 代碼:
          const takeRight = (arr, n = 1) => arr.slice(arr.length - n, arr.length);// takeRight([1, 2, 3], 2) -> [ 2, 3 ]// takeRight([1, 2, 3]) -> [3]

          Take(從一個(gè)給定的數(shù)組中創(chuàng)建一個(gè)前N個(gè)元素的數(shù)組)

          使用 Array.slice()?創(chuàng)建一個(gè)數(shù)組包含第一個(gè)元素開(kāi)始,到 n 個(gè)元素結(jié)束的數(shù)組。
          JavaScript 代碼:
          const take = (arr, n = 1) => arr.slice(0, n);// take([1, 2, 3], 5) -> [1, 2, 3]// take([1, 2, 3], 0) -> []

          Unique values of array (數(shù)組去重)

          使用 ES6 的 Set 和 ...rest 操作符剔除重復(fù)的值。
          JavaScript 代碼:
          const unique = arr => [...new Set(arr)];// unique([1,2,2,3,4,4,5]) -> [1,2,3,4,5]

          Browser 瀏覽器

          Bottom visible (頁(yè)面的底部是否可見(jiàn))

          使用 scrollY,scrollHeight 和 clientHeight 來(lái)確定頁(yè)面的底部是否可見(jiàn)。
          JavaScript 代碼:
          const bottomVisible = _ => document.documentElement.clientHeight + window.scrollY >= document.documentElement.scrollHeight || document.documentElement.clientHeight;// bottomVisible() -> true

          Current URL (獲取當(dāng)前頁(yè)面URL)

          使用 window.location.href 獲取當(dāng)前頁(yè)面URL。
          JavaScript 代碼:
          const currentUrl = _ => window.location.href;// currentUrl() -> 'https://google.com'

          Element is visible in viewport (判斷元素是否在可視窗口可見(jiàn))

          使用 Element.getBoundingClientRect()?和 window.inner(Width|Height)?值來(lái)確定給定元素是否在可視窗口中可見(jiàn)。省略第二個(gè)參數(shù)來(lái)判斷元素是否完全可見(jiàn),或者指定 true 來(lái)判斷它是否部分可見(jiàn)。
          JavaScript 代碼:
          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;};// 舉個(gè)例子,有一個(gè) 100x100 可視窗口, 和一個(gè) 10x10px 元素定位在 {top: -1, left: 0, bottom: 9, right: 10}// elementIsVisibleInViewport(el) -> false (not fully visible)// elementIsVisibleInViewport(el, true) -> true (partially visible)

          Get scroll position (獲取滾動(dòng)條位置)

          如果瀏覽器支持 pageXOffset 和 pageYOffset ,那么請(qǐng)使用 pageXOffset 和 pageYOffset ,否則請(qǐng)使用 scrollLeft 和 scrollTop 。你可以省略 el 參數(shù),默認(rèn)值為 window。
          JavaScript 代碼:
          const getScrollPos = (el = window) => ({x: (el.pageXOffset !== undefined) ? el.pageXOffset : el.scrollLeft, y: (el.pageYOffset !== undefined) ? el.pageYOffset : el.scrollTop});// getScrollPos() -> {x: 0, y: 200}

          Redirect to URL (重定向到URL)

          使用 window.location.href 或 window.location.replace()?重定向到 url 。傳遞第二個(gè)參數(shù)來(lái)模擬鏈接點(diǎn)擊(true – 默認(rèn)值)或HTTP重定向(false)。
          JavaScript 代碼:
          const redirect = (url, asLink = true) => asLink ? window.location.href = url : window.location.replace(url);// redirect('https://google.com')

          Scroll to top (回到頂部)

          使用 document.documentElement.scrollTop 或 document.body.scrollTop 獲取到頂部距離。從頂部滾動(dòng)一小部分距離。使用window.requestAnimationFrame()?來(lái)實(shí)現(xiàn)滾動(dòng)動(dòng)畫(huà)。
          JavaScript 代碼:
          const scrollToTop = _ => { const c = document.documentElement.scrollTop || document.body.scrollTop; if (c > 0) { window.requestAnimationFrame(scrollToTop); window.scrollTo(0, c - c / 8); }};// scrollToTop()

          Date 日期

          Get days difference between dates (獲取兩個(gè)日期之間相差的天數(shù))

          計(jì)算 Date 對(duì)象之間的差異(以天為單位)。
          JavaScript 代碼:
          const getDaysDiffBetweenDates = (dateInitial, dateFinal) => (dateFinal - dateInitial) / (1000 * 3600 * 24);// getDaysDiffBetweenDates(new Date("2017-12-13"), new Date("2017-12-22")) -> 9

          Function 函數(shù)

          Chain asynchronous functions (鏈?zhǔn)秸{(diào)用異步函數(shù))

          循環(huán)遍歷包含異步事件的函數(shù)數(shù)組,每次異步事件完成后調(diào)用 next 。
          JavaScript 代碼:
          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'); }])*/

          Curry (函數(shù)式編程術(shù)語(yǔ):柯里化)

          使用遞歸。如果提供的參數(shù)(args)數(shù)量足夠,調(diào)用傳遞函數(shù) fn 。否則返回一個(gè)柯里化后的函數(shù) fn ,期望剩下的參數(shù)。
          如果你想柯里化一個(gè)接受可變參數(shù)數(shù)量的函數(shù)(可變參數(shù)數(shù)量的函數(shù),例如 Math.min()?),你可以選擇將參數(shù)個(gè)數(shù)傳遞給第二個(gè)參數(shù) arity。
          JavaScript 代碼:
          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

          Pipe (函數(shù)式編程術(shù)語(yǔ):管道或?qū)Я?

          使用 Array.reduce()?來(lái)執(zhí)行從左到右的函數(shù)組合。第一個(gè)(最左邊的)函數(shù)可以接受一個(gè)或多個(gè)參數(shù);其余的函數(shù)必須是一元函數(shù)。
          JavaScript 代碼:
          const pipe = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args)));/*const add5 = x => x + 5const multiply = (x, y) => x * yconst multiplyAndAdd5 = pipe(multiply, add5)multiplyAndAdd5(5, 2) -> 15*/

          Promisify (柯里化一個(gè) Promise 函數(shù))

          使用柯里化返回一個(gè)函數(shù),這個(gè)函數(shù)返回一個(gè)調(diào)用原始函數(shù)的 Promise 。使用 ...rest 運(yùn)算符傳入所有參數(shù)。
          在 Node 8+ 中,你可以使用?util.promisify
          JavaScript 代碼:
          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

          Run promises in series (運(yùn)行連續(xù)的 promises)

          使用 Array.reduce()?通過(guò)創(chuàng)建 promise 鏈來(lái)運(yùn)行連續(xù)的 promises,其中每個(gè) promise 在 resolved 時(shí)返回下一個(gè) promise 。
          JavaScript 代碼:
          const series = ps => ps.reduce((p, next) => p.then(next), Promise.resolve());// const delay = (d) => new Promise(r => setTimeout(r, d))// series([() => delay(1000), () => delay(2000)]) -> executes each promise sequentially, taking a total of 3 seconds to complete

          Sleep (休眠)

          延遲執(zhí)行 async 函數(shù)的一部分,通過(guò)把它放到 sleep 狀態(tài),返回一個(gè) Promise 。
          JavaScript 代碼:
          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.');}*/

          Math 數(shù)學(xué)方法

          Collatz algorithm(考拉茲算法)

          如果 n 是偶數(shù),則返回 n/2 。否則返回 3n+1 。
          JavaScript 代碼:
          const collatz = n => (n % 2 == 0) ? (n / 2) : (3 * n + 1);// collatz(8) --> 4// collatz(5) --> 16
          注:考拉茲猜想(英語(yǔ):Collatz conjecture),又稱為奇偶?xì)w一猜想、3n+1猜想、冰雹猜想、角谷猜想、哈塞猜想、烏拉姆猜想或敘拉古猜想,是指對(duì)于每一個(gè)正整數(shù),如果它是奇數(shù),則對(duì)它乘3再加1,如果它是偶數(shù),則對(duì)它除以2,如此循環(huán),最終都能夠得到1。– 維基百科。

          Distance between two points (兩點(diǎn)之間的歐氏距離)

          使用 Math.hypot()?計(jì)算兩點(diǎn)之間的歐氏距離( Euclidean distance)。
          JavaScript 代碼:
          const distance = (x0, y0, x1, y1) => Math.hypot(x1 - x0, y1 - y0);// distance(1,1, 2,3) -> 2.23606797749979
          注:歐氏距離( Euclidean distance)是一個(gè)通常采用的距離定義,它是在m維空間中兩個(gè)點(diǎn)之間的真實(shí)距離。

          Divisible by number (可以被某個(gè)數(shù)整除)

          使用模運(yùn)算符(%)來(lái)檢查余數(shù)是否等于?0?。
          JavaScript 代碼:
          const isDivisible = (dividend, divisor) => dividend % divisor === 0;// isDivisible(6,3) -> true

          Even or odd number (判斷奇偶數(shù))

          使用模運(yùn)算符(%)來(lái)檢查數(shù)字是奇數(shù)還是偶數(shù)。如果數(shù)字是偶數(shù),則返回 true ,如果是奇數(shù),則返回 false 。
          JavaScript 代碼:
          const isEven = num => num % 2 === 0;// isEven(3) -> false

          Factorial (階乘)

          使用遞歸。如果 n 小于或等于 1 ,則返回 1 。否則返回 n 和 n - 1 的階乘。
          JavaScript 代碼:
          const factorial = n => n < = 1 ? 1 : n * factorial(n - 1);// factorial(6) -> 720

          Fibonacci array generator (斐波納契數(shù)組發(fā)生器)

          創(chuàng)建一個(gè)指定長(zhǎng)度的空數(shù)組,初始化前兩個(gè)值(?0?和 1 )。使用 Array.reduce()?向數(shù)組中添加值,使用最的值是兩個(gè)值的和(前兩個(gè)除外)。
          JavaScript 代碼:
          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]

          Greatest common divisor (GCD) (最大公約數(shù))

          使用遞歸。當(dāng) y 等于?0?的情況下,返回 x 。否則,返回 y 和 x/y 余數(shù)最大公約數(shù)。
          JavaScript 代碼:
          const gcd = (x, y) => !y ? x : gcd(y, x % y);// gcd (8, 36) -> 4

          Hamming distance (漢明距離)

          使用XOR運(yùn)算符(?^?)查找這兩個(gè)數(shù)字之間的位差,使用 toString(2)?轉(zhuǎn)換為二進(jìn)制字符串。使用 match(/1/g)?計(jì)算并返回字符串中 1 的數(shù)量。
          JavaScript 代碼:
          const hammingDistance = (num1, num2) => ((num1 ^ num2).toString(2).match(/1/g) || '').length;// hammingDistance(2,3) -> 1
          注:在信息論中,兩個(gè)等長(zhǎng)字符串之間的漢明距離(英語(yǔ):Hamming distance)是兩個(gè)字符串對(duì)應(yīng)位置的不同字符的個(gè)數(shù)。換句話說(shuō),它就是將一個(gè)字符串變換成另外一個(gè)字符串所需要替換的字符個(gè)數(shù)。- 維基百科

          Percentile (百分比)

          使用 Array.reduce()?來(lái)計(jì)算有多少數(shù)字小于等于該值,并用百分比表示。
          JavaScript 代碼:
          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 (冪集)

          使用 Array.reduce()?與 Array.map()?結(jié)合來(lái)遍歷元素,并將其組合成一個(gè)包含所有排列組合的數(shù)組。
          JavaScript 代碼:
          const powerset = arr => arr.reduce((a, v) => a.concat(a.map(r => [v].concat(r))), [[]]);// powerset([1,2]) -> [[], [1], [2], [2,1]]

          Round number to n digits (精確的幾位小數(shù))

          使用 Math.round()?和模板字面量將數(shù)字四舍五入為指定的小數(shù)位數(shù)。省略第二個(gè)參數(shù) decimals ,數(shù)字將被四舍五入到一個(gè)整數(shù)。
          JavaScript 代碼:
          const round = (n, decimals=0) => Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`);// round(1.005, 2) -> 1.01

          Standard deviation (標(biāo)準(zhǔn)偏差)

          使用 Array.reduce()?來(lái)計(jì)算均值,方差已經(jīng)值的方差之和,方差的值,然后確定標(biāo)準(zhǔn)偏差。您可以省略第二個(gè)參數(shù)來(lái)獲取樣本標(biāo)準(zhǔn)偏差,或?qū)⑵湓O(shè)置為 true 以獲得總體標(biāo)準(zhǔn)偏差。
          JavaScript 代碼:
          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)

          Media 媒體

          Speech synthesis (語(yǔ)音合成,實(shí)驗(yàn)階段)

          使用 SpeechSynthesisUtterance.voice 和 indow.speechSynthesis.getVoices()?將消息轉(zhuǎn)換為語(yǔ)音。使用 window.speechSynthesis.speak()?播放消息。
          了解有關(guān)Web Speech API的SpeechSynthesisUtterance接口的更多信息。
          JavaScript 代碼:
          const speak = message => { const msg = new SpeechSynthesisUtterance(message); msg.voice = window.speechSynthesis.getVoices()[0]; window.speechSynthesis.speak(msg);};// speak('Hello, World') -> plays the message

          Node

          Write JSON to file (將 JSON 寫(xiě)到文件)

          使用 fs.writeFile(),模板字面量 和 JSON.stringify()?將 json 對(duì)象寫(xiě)入到 .json 文件中。
          JavaScript 代碼:
          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'

          Object 對(duì)象

          Object from key-value pairs (根據(jù)鍵值對(duì)創(chuàng)建對(duì)象)

          使用 Array.reduce()?來(lái)創(chuàng)建和組合鍵值對(duì)。
          JavaScript 代碼:
          const objectFromPairs = arr => arr.reduce((a, v) => (a[v[0]] = v[1], a), {});// objectFromPairs([['a',1],['b',2]]) -> {a: 1, b: 2}

          Object to key-value pairs (對(duì)象轉(zhuǎn)化為鍵值對(duì) )

          使用 Object.keys()?和 Array.map()?遍歷對(duì)象的鍵并生成一個(gè)包含鍵值對(duì)的數(shù)組。
          JavaScript 代碼:
          const objectToPairs = obj => Object.keys(obj).map(k => [k, obj[k]]);// objectToPairs({a: 1, b: 2}) -> [['a',1],['b',2]])

          Shallow clone object (淺克隆對(duì)象)

          使用 Object.assign()?和一個(gè)空對(duì)象({})來(lái)創(chuàng)建原始對(duì)象的淺拷貝。
          JavaScript 代碼:
          const shallowClone = obj => Object.assign({}, obj);/*const a = { x: true, y: 1 };const b = shallowClone(a);a === b -> false*/
          注:JavaScript 中的對(duì)象拷貝方法有很多,這里有個(gè)總結(jié),有興趣可以看一下:https://www.html.cn/archives/8319

          String 字符串

          Anagrams of string (with duplicates) (字符串的排列組合,帶有重復(fù)項(xiàng))

          使用遞歸。對(duì)于給定字符串中的每個(gè)字母,為其余字母創(chuàng)建所有部分字母。使用 Array.map()?將字母與每個(gè)部分字母組合在一起,然后使用 Array.reduce()?將所有字母組合到一個(gè)數(shù)組中。基本情況是字符串 length 等于 2 或 1 。
          JavaScript 代碼:
          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 first letter of every word (大寫(xiě)每個(gè)單詞的首字母)

          使用 replace()?來(lái)匹配每個(gè)單詞的第一個(gè)字符,并使用 toUpperCase()?來(lái)將其大寫(xiě)。
          JavaScript 代碼:
          const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperCase());// capitalizeEveryWord('hello world!') -> 'Hello World!'

          Capitalize first letter (首字母大寫(xiě))

          使用解構(gòu)和 toUpperCase()?大寫(xiě)第一個(gè)字母,...rest 第一個(gè)字母后獲得字符數(shù)組,然后 Array.join('')再次使它成為一個(gè)字符串。省略 lowerRest 參數(shù)以保持字符串的剩余部分不變,或者將其設(shè)置為 true 這會(huì)將字符串的剩余部分轉(zhuǎn)換為小寫(xiě)。
          JavaScript 代碼:
          const capitalize = ([first,...rest], lowerRest = false) => first.toUpperCase() + (lowerRest ? rest.join('').toLowerCase() : rest.join(''));// capitalize('myName') -> 'MyName'// capitalize('myName', true) -> 'Myname'

          Check for palindrome (檢查回文)

          使用 toLowerCase()?轉(zhuǎn)換字符串,并使用 replace()?從中刪除非字母數(shù)字字符。然后,在將其轉(zhuǎn)換為 tolowerCase()?之后,將 split('')?為單獨(dú)的字符,reverse()?,join('')并與原始非反轉(zhuǎn)字符串進(jìn)行比較。
          JavaScript 代碼:
          const palindrome = str => { const s = str.toLowerCase().replace(/[\W_]/g,''); return s === s.split('').reverse().join('');}// palindrome('taco cat') -> true

          Reverse a string (反轉(zhuǎn)一個(gè)字符串)

          使用數(shù)組解構(gòu)和 Array.reverse()?來(lái)反轉(zhuǎn)字符串中字符的順序。使用 join('')合并字符串。
          JavaScript 代碼:
          const reverseString = str => [...str].reverse().join('');// reverseString('foobar') -> 'raboof'

          Sort characters in string (alphabetical) (按字母順序排列字符串)

          使用 split('')?分割字符串,通過(guò) localeCompare()?排序字符串 Array.sort()?,使用 join('')?進(jìn)行重組。
          JavaScript 代碼:
          const sortCharactersInString = str => str.split('').sort((a, b) => a.localeCompare(b)).join('');// sortCharactersInString('cabbage') -> 'aabbceg'

          Truncate a String (截?cái)嘁粋€(gè)字符串)

          確定字符串的 length 是否大于 num。返回截?cái)嗨栝L(zhǎng)度的字符串,用 ... 附加到結(jié)尾或原始字符串。
          JavaScript 代碼:
          const truncate = (str, num) => str.length > num ? str.slice(0, num > 3 ? num - 3 : num) + '...' : str;// truncate('boomerang', 7) -> 'boom...'

          Utility 實(shí)用函數(shù)

          Escape regular expression (轉(zhuǎn)義正則表達(dá)式)

          使用 replace()?來(lái)轉(zhuǎn)義特殊字符。
          JavaScript 代碼:
          const escapeRegExp = str => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');// escapeRegExp('(test)') -> \\(test\\)

          Get native type of value (獲取原生類型的值)

          返回值小寫(xiě)的構(gòu)造函數(shù)名稱,如果值為 undefined 或 null ,則返回 “undefined” 或 “null”。
          JavaScript 代碼:
          const getType = v => v === undefined ? 'undefined' : v === null ? 'null' : v.constructor.name.toLowerCase();// getType(new Set([1,2,3])) -> "set"

          Hexcode to RGB (Hex轉(zhuǎn)RGB)

          使用Array.slice() , Array.map()?和 match()?將十六進(jìn)制顏色代碼(前綴為#)轉(zhuǎn)換為RGB值的字符串。
          JavaScript 代碼:
          const hexToRgb = hex => `rgb(${hex.slice(1).match(/.{2}/g).map(x => parseInt(x, 16)).join()})`// hexToRgb('#27ae60') -> 'rgb(39,174,96)'

          Is array(是否為數(shù)組)

          使用 Array.isArray()?來(lái)檢查一個(gè)值是否為一個(gè)數(shù)組。
          JavaScript 代碼:
          const isArray = val => !!val && Array.isArray(val);// isArray(null) -> false// isArray([1]) -> true

          Is boolean(是否為布爾值)

          使用 typeof 來(lái)檢查一個(gè)值是否為一個(gè)布爾值。
          JavaScript 代碼:
          const isBoolean = val => typeof val === 'boolean';// isBoolean(null) -> false// isBoolean(false) -> true

          Is function(是否為函數(shù))

          使用 typeof 來(lái)檢查一個(gè)值是否為一個(gè)函數(shù)。
          JavaScript 代碼:
          const isFunction = val => val && typeof val === 'function';// isFunction('x') -> false// isFunction(x => x) -> true

          Is number(是否為數(shù)字)

          使用 typeof 來(lái)檢查一個(gè)值是否為一個(gè)數(shù)字。
          JavaScript 代碼:
          const isNumber = val => typeof val === 'number';// isNumber('1') -> false// isNumber(1) -> true

          Is string(是否為字符串)

          使用 typeof 來(lái)檢查一個(gè)值是否為一個(gè)字符串。
          JavaScript 代碼:
          const isString = val => typeof val === 'string';// isString(10) -> false// isString('10') -> true

          Is symbol(是否為symbol)

          使用 typeof 來(lái)檢查一個(gè)值是否為一個(gè) symbol 。
          JavaScript 代碼:
          const isSymbol = val => typeof val === 'symbol';// isSymbol('x') -> false// isSymbol(Symbol('x')) -> true

          Measure time taken by function (計(jì)算函數(shù)執(zhí)行所花費(fèi)的時(shí)間)

          使用 console.time()?和 console.timeEnd()?來(lái)測(cè)量開(kāi)始和結(jié)束時(shí)間之間的差,以確定回調(diào)執(zhí)行的時(shí)間。
          JavaScript 代碼:
          const timeTaken = callback => { console.time('timeTaken'); const r = callback(); console.timeEnd('timeTaken'); return r;};// timeTaken(() => Math.pow(2, 10)) -> 1024// (logged): timeTaken: 0.02099609375ms

          Number to array of digits (將數(shù)字轉(zhuǎn)化為整數(shù)數(shù)組)

          將數(shù)字轉(zhuǎn)換為字符串,使用 split()?來(lái)轉(zhuǎn)換構(gòu)建一個(gè)數(shù)組。使用 Array.map()?和 parseInt()?將每個(gè)值轉(zhuǎn)換為整數(shù)。
          JavaScript 代碼:
          const digitize = n => (''+n).split('').map(i => parseInt(i));// digitize(2334) -> [2, 3, 3, 4]

          Ordinal suffix of number (數(shù)字序號(hào)的后綴)

          使用模運(yùn)算符(%)來(lái)查找各位和十位的值。查找哪些序號(hào)模式數(shù)字匹配。如果數(shù)字在十位模式中找到,請(qǐng)使用十位的序數(shù)。
          JavaScript 代碼:
          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"

          Random integer in range (在指定的范圍內(nèi)生成一個(gè)隨機(jī)整數(shù))

          使用 Math.random()?生成一個(gè)隨機(jī)數(shù)并將其映射到所需的范圍,使用 Math.floor()?使其成為一個(gè)整數(shù)。
          JavaScript 代碼:
          const randomIntegerInRange = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;// randomIntegerInRange(0, 5) -> 2

          Random number in range (在指定的范圍內(nèi)生成一個(gè)隨機(jī)數(shù))

          使用 Math.random()?生成一個(gè)隨機(jī)值,使用乘法將其映射到所需的范圍。
          JavaScript 代碼:
          const randomInRange = (min, max) => Math.random() * (max - min) + min;// randomInRange(2,10) -> 6.0211363285087005

          RGB to hexadecimal(RGB轉(zhuǎn)hex)

          使用按位左移運(yùn)算符(<<)和 toString(16)?將給定的RGB參數(shù)轉(zhuǎn)換為十六進(jìn)制字符串,然后使用 padStart(6,'0')?得到一個(gè)6位的十六進(jìn)制值。
          JavaScript 代碼:
          const rgbToHex = (r, g, b) => ((r << 16) + (g << 8) + b).toString(16).padStart(6, '0');// rgbToHex(255, 165, 1) -> 'ffa501'

          Swap values of two variables (交換兩個(gè)變量的值)

          使用數(shù)組解構(gòu)來(lái)交換兩個(gè)變量之間的值。
          JavaScript 代碼:
          [varA, varB] = [varB, varA];// [x, y] = [y, x]

          URL parameters(網(wǎng)址參數(shù))

          通過(guò)適當(dāng)?shù)恼齽t表達(dá)式,使用 match()?來(lái)獲得所有的鍵值對(duì), Array.reduce()?來(lái)映射和組合成一個(gè)單一的對(duì)象。將 location.search 作為參數(shù)傳遞給當(dāng)前 url。
          JavaScript 代碼:
          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'}

          UUID generator (UUID生成器)

          使用?crypto?API 生成符一個(gè) UUID,符合RFC4122?版本 4 。
          JavaScript 代碼:
          const uuid = _ => ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c => (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16) );// uuid() -> '7982fcfe-5721-4632-bede-6000885be57d'

          Validate email(郵箱驗(yàn)證)

          使用正則表達(dá)式來(lái)檢查電子郵件是否有效。如果電子郵件有效,則返回 true ,否則返回false 。
          JavaScript 代碼:
          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([email protected]) -> true

          Validate number (數(shù)字驗(yàn)證)

          使用 !isNaN 和 parseFloat()?來(lái)檢查參數(shù)是否是一個(gè)數(shù)字。使用 isFinite()?來(lái)檢查數(shù)字是否是有限數(shù)。使用 Number()?來(lái)檢查強(qiáng)制轉(zhuǎn)換是否成立。
          JavaScript 代碼:
          const validateNumber = n => !isNaN(parseFloat(n)) && isFinite(n) && Number(n) == n;// validateNumber('10') -> true

          Value or default (值或者默認(rèn)值)

          返回 value ,如果傳遞的值是 falsy ,則返回默認(rèn)值。
          JavaScript 代碼:
          const valueOrDefault = (value, d) => value || d;// valueOrDefault(NaN, 30) -> 30
          本文完~


          瀏覽 65
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          評(píng)論
          圖片
          表情
          推薦
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  在线国产激情视频 | 九色91视频 | 欧美大黄视频 | 操b操逼| 黄色性爱视频欧美 |