127個常用的JS代碼片段,每段代碼花30秒就能看懂(二)


127個常用的JS代碼片段,每段代碼花30秒就能看懂(二)

大家好,在上一篇文章 裡,我分享了前21段代碼,今天繼續分享21段代碼,希望對你的日常工作有所幫助。

22、deepFlatten

通過遞歸的形式,將多維數組展平成一維數組。

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

23、default

去重對象的屬性,如果對象中含有重複的屬性,以前面的為準。

<code>const defaults = (obj, ...defs) => Object.assign({}, obj, ...defs.reverse(), obj);defaults({ a: 1 }, { b: 2 }, { b: 6 }, { a: 3 }); // { a: 1, b: 2 }/<code>

24、defer

延遲函數的調用,即異步調用函數。

<code>const defer = (fn, ...args) => setTimeout(fn, 1, ...args);defer(console.log, 'a'), console.log('b'); // logs 'b' then 'a'/<code>

25、degreesToRads

此段代碼將標準的度數,轉換成弧度。

<code>const degreesToRads = deg => (deg * Math.PI) / 180.0;degreesToRads(90.0); // ~1.5708/<code>

26、difference

此段代碼查找兩個給定數組的差異,查找出前者數組在後者數組中不存在元素。

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

27、differenceBy

通過給定的函數來處理需要對比差異的數組,查找出前者數組在後者數組中不存在元素。

<code>const differenceBy = (a, b, fn) => {  const s = new Set(b.map(fn));  return a.filter(x => !s.has(fn(x)));};differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); // [1.2]differenceBy([{ x: 2 }, { x: 1 }], [{ x: 1 }], v => v.x); // [ { x: 2 } ]/<code>

28、differenceWith

此段代碼按照給定函數邏輯篩選需要對比差異的數組,查找出前者數組在後者數組中不存在元素。

<code>const differenceWith = (arr, val, comp) => arr.filter(a => val.findIndex(b => comp(a, b)) === -1);differenceWith([1, 1.2, 1.5, 3, 0], [1.9, 3, 0], (a, b) => Math.round(a) === Math.round(b)); // [1, 1.2]/<code>

29、digitize

將輸入的數字拆分成單個數字組成的數組。

<code>const digitize = n => [...`${n}`].map(i => parseInt(i));digitize(431); // [4, 3, 1]/<code>

30、distance

計算兩點之間的距離

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

31、drop

此段代碼將給定的數組從左邊開始刪除 n 個元素

<code>const drop = (arr, n = 1) => arr.slice(n);drop([1, 2, 3]); // [2,3]drop([1, 2, 3], 2); // [3]drop([1, 2, 3], 42); // []/<code>

32、dropRight

此段代碼將給定的數組從右邊開始刪除 n 個元素

<code>const dropRight = (arr, n = 1) => arr.slice(0, -n);dropRight([1, 2, 3]); // [1,2]dropRight([1, 2, 3], 2); // [1]dropRight([1, 2, 3], 42); // []/<code> 

33、dropRightWhile

此段代碼將給定的數組按照給定的函數條件從右開始刪除,直到當前元素滿足函數條件為True時,停止刪除,並返回數組剩餘元素。

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

34、dropWhile

按照給的的函數條件篩選數組,不滿足函數條件的將從數組中移除。

<code>const dropWhile = (arr, func) => {  while (arr.length > 0 && !func(arr[0])) arr = arr.slice(1);  return arr;};dropWhile([1, 2, 3, 4], n => n >= 3); // [3,4]/<code>

35、elementContains

接收兩個DOM元素對象參數,判斷後者是否是前者的子元素。

<code>const elementContains = (parent, child) => parent !== child && parent.contains(child);elementContains(document.querySelector('head'), document.querySelector('title')); // trueelementContains(document.querySelector('body'), document.querySelector('body')); // false/<code>

36、filterNonUnique

移除數組中重複的元素

<code>const filterNonUnique = arr => [ …new Set(arr)];filterNonUnique([1, 2, 2, 3, 4, 4, 5]); // [1, 2, 3, 4, 5]/<code>

37、findKey

按照給定的函數條件,查找第一個滿足條件對象的鍵值。

<code>const findKey = (obj, fn) => Object.keys(obj).find(key => fn(obj[key], key, obj));findKey(  {    barney: { age: 36, active: true },    fred: { age: 40, active: false },    pebbles: { age: 1, active: true }  },  o => o['active']); // 'barney'/<code>

38、findLast

按照給定的函數條件篩選數組,將最後一個滿足條件的元素進行刪除。

<code>const findLast = (arr, fn) => arr.filter(fn).pop();findLast([1, 2, 3, 4], n => n % 2 === 1); // 3/<code>

39、flatten

按照指定數組的深度,將嵌套數組進行展平。

<code>const flatten = (arr, depth = 1) =>  arr.reduce((a, v) => a.concat(depth > 1 && Array.isArray(v) ? flatten(v, depth - 1) : v), []);flatten([1, [2], 3, 4]); // [1, 2, 3, 4]flatten([1, [2, [3, [4, 5], 6], 7], 8], 2); // [1, 2, 3, [4, 5], 6, 7, 8]/<code>

40、forEachRight

按照給定的函數條件,從數組的右邊往左依次進行執行。

<code>const forEachRight = (arr, callback) =>  arr    .slice(0)    .reverse()    .forEach(callback);    forEachRight([1, 2, 3, 4], val => console.log(val)); // '4', '3', '2', '1'/<code>

41、forOwn

此段代碼按照給定的函數條件,進行迭代對象。

<code>const forOwn = (obj, fn) => Object.keys(obj).forEach(key => fn(obj[key], key, obj));forOwn({ foo: 'bar', a: 1 }, v => console.log(v)); // 'bar', 1/<code>

42、functionName

此段代碼輸出函數的名稱。

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

小節

今天的內容就和大家分享到這裡,感謝你的閱讀,如果你喜歡我的分享,麻煩給個關注、點贊加轉發哦,你的支持,就是我分享的動力,後續會持續分享剩餘的代碼片段,歡迎持續關注。

本文原作者:Fatos Morina

來源網站:medium

注:並非直譯


分享到:


相關文章: