18個常用的JavaScript片段分享

千鋒武漢發表於2021-08-16

JavaScript,這種強大的語言幾乎涉及到程式設計各個方面:前端、後端、web應用程式、桌面應用程式、移動應用程式等等。 小千整理了18個常用的JavaScript片段分享給大家,在日常開發工作中,它們將為你大大節省時間。

u=1894241208,139720229&fm=26&fmt=auto&gp=0.webp

1. maxItemOfArray

獲取陣列中的最大數字

const maxItemOfArray = (arr) => arr.sort((a, b) => b - a)[0];let maxItem = maxItemOfArray([3, 5, 12, 5]);

2. areAllEqual

檢查陣列的所有項是否相等

const areAllEqual = array => array.every(item => item === array[0]);

let check1 = areAllEqual([3, 5, 2]); // false

let check2 = allEqual([3, 3, 3]); // true

3. averageOf

求給定數字的平均值

const averageOf = (…numbers) => numbers.reduce((a, b) => a + b, 0) / numbers.length;

let average = averageOf(5, 2, 4, 7); // 4.5

4. reverseString

反轉一個字串

const reverseString = str => […str].reverse().join(‘’);

let a = reverseString(‘Have a nice day!’); // !yad ecin a evaH

5. sumOf

求給定數字的和

const sumOf = (…numbers) => numbers.reduce((a, b) => a + b, 0);

let sum = sumOf(5, -3, 2, 1); // 5

6. findAndReplace

在字串中查詢給定的單詞,並替換為另一個單詞

const findAndReplace = (string, wordToFind, wordToReplace) => string.split(wordToFind).join(wordToReplace);

let result = findAndReplace(‘I like banana’, ‘banana’, ‘apple’); // I like apple

7. RGBToHex

將RGB模式下的顏色轉換為十六進位制

const RGBToHex = (r, g, b) => ((r << 16) + (g << 8) + b).toString(16).padStart(6, ‘0’);

let hex = RGBToHex(255, 255, 255); // ffffff

8. shuffle

音樂播放器如何隨機播放播放專案?

const shuffle = ([…array]) => {

let m = array.length;

while (m) {

const i = Math.floor(Math.random() * m — );

[array[m], array[i]] = [array[i], array[m]];

}

return array;

};

shuffle([5, 4, 3, 6, 20]);

9. removeFalseValues

從陣列中刪除false值,包括false,undefined,NaN,empty

const removeFalseValues = arr => arr.filter(item => item);

let arr = removeFalseValues([3, 4, false, ‘’, 5, true, undefined, NaN, ‘’]); // [3, 4, 5, true]

10. removeDuplicatedValues

從陣列中刪除重複的項

const removeDuplicatedValues = array => […new Set(array)];

let arr = removeDuplicatedValues([5, 3, 2, 5, 6, 1, 1, 6]); // [5, 3, 2, 6, 1]

11. getTimeFromDate

以日期物件的字串形式返回時間

const getTimeFromDate = date => date.toTimeString().slice(0, 8);

let time = getTimeFromDate(new Date()); // 09:46:08

12. capitalizeAllWords

將字串中所有單詞的首個字母大寫

const capitalizeAllWords = str => str.replace(/\b[a-z]/g, char => char.toUpperCase());

let str = capitalizeAllWords(‘i love reading book’); // I Love Reading Book

13. getDayDiff

返回兩個日期之間以天為單位的差值

const getDayDiff = (date1, date2) => ((date2 - date1) / (1000 * 3600 * 24));let diff = getDayDiff(new Date('2020-04-01'), new Date('2020-08-15')); // 136

14. radianToDegree

把弧度轉換成角度

const radianToDegree = radian => (radian * 180.0) / Math.PI;let degree = radianToDegree(2.3); // 131.78

15. isValidJSON

檢查給定字串是否是有效的JSON

const isValidJSON = string => { try { JSON.parse(string); return true; } catch (error) { return false; }};let check1 = isValidJSON(‘{“title”: “javascript”, “price”: 14}’); // truelet check2 = isValidJSON(‘{“title”: “javascript”, “price”: 14, sub title}’); // false

16. toWords

將給定的字串轉換為單詞陣列

const toWords = (string, pattern = /[^a-zA-Z-]+/) => string.split(pattern).filter(item => item);

let words = toWords(‘I want to be come a great programmer’); // [“I”, “want”,“to”, “be”, “come”, “a”, “great”, “programmer”]

17. scrollToTop

位於長頁面的底部,並且想快速向上滾動至頂部

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

18. isValidNumber

驗證數字是否有效

const isValidNumber = n => !isNaN(parseFloat(n)) && isFinite(n) && Number(n) =

本文來自千鋒教育,轉載請註明出處。

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/31548651/viewspace-2787064/,如需轉載,請註明出處,否則將追究法律責任。

相關文章