28 個常見的JavaScript開發(fā)技巧

英文 | https://niemvuilaptrinh.medium.com/28-tip-javascript-you-should-know-5c8ca83e4f99
翻譯 | 楊小愛

以下是代碼:
/*niemvuilaptrinh.com*/const stringReverse = str => str.split("").reverse().join("");stringReverse('hello world'); /*dlrow olleh*/
2、滾動到頁面頂部

以下是代碼:
/*niemvuilaptrinh.com*/const scrollToTop = () => window.scrollTo(0, 0);scrollToTop();
3、刪除數(shù)組中的重復項

/*niemvuilaptrinh.com*/const removeDuplicate = (arr) => [...new Set(arr)];removeDuplicate([1, 2, 3, 4, 4, 2, 1]); // [1, 2, 3, 4]
4、獲取數(shù)組中的隨機項

/*niemvuilaptrinh.com*/const randomItemArray = (arr) => arr[Math.floor(Math.random() * arr.length)];randomItemArray(['a', 'b', 'c', 1, 2, 3]);
5、獲取數(shù)組中的最大數(shù)

/*niemvuilaptrinh.com*/const maxNumber = (arr, n = 1) => [...arr].sort((a, b) => b - a).slice(0, n);maxNumber([4,9,5,7,2]) /* 9 */
6、 檢查型號

以下是代碼:
/*niemvuilaptrinh.com*/function isNumber(num) {return !isNaN(parseFloat(num)) && isFinite(num);}isNumber("Hello"); /*false*/isNumber(123);/*true*/
7、檢查類型為空

/*niemvuilaptrinh.com*/const checkNull = val => val === undefined || val === null;checkNull(123) /* false */checkNull() /* true */checkNull('hello') /* false */
8、獲取數(shù)組中的最小數(shù)

/*niemvuilaptrinh.com*/const minNumber = (arr, n = 1) => [...arr].sort((a, b) => a - b).slice(0, n);console.log(minNumber([3,5,9,7,1])) /*1*/
9、 獲取數(shù)組中的平均數(shù)

/*niemvuilaptrinh.com*/const averageNumber = arr => arr.reduce((a, b) => a + b) / arr.length;averageNumber([1, 2, 3, 4, 5]) /* 3 */
10、檢查元素的類型

/*niemvuilaptrinh.com*//*niemvuilaptrinh.com*/ const checkType = v => v === undefined ? 'undefined' : v === null ? 'null' : v.constructor.name.toLowerCase();checkType(true) /*boolean*/checkType("hello World") /*string*/checkType(123) /*number*/
11、計算數(shù)組中元素的出現(xiàn)次數(shù)

/*niemvuilaptrinh.com*/const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a), 0);countOccurrences([1,2,2,4,5,6,2], 2) /* S? 2 xu?t hi?n 3 l?n trong array */
12、使用 Javascript 獲取當前 URL

/*niemvuilaptrinh.com*/const getCurrentURL = () => window.location.href;getCurrentURL() /* https://www.niemvuilaptrinh.com */
13、大寫字符串中的字母

以下是代碼:
/*niemvuilaptrinh.com*/const capitalizeString = str => str.replace(/b[a-z]/g, char => char.toUpperCase());capitalizeString('niem vui lap trinh'); /* 'Niem Vui Lap Trinh' */
14、將 RGB 轉(zhuǎn)換為十六進制

/*niemvuilaptrinh.com*/const rgbToHex = (r, g, b) => "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);rgbToHex(52, 45, 125); /* K?t qu? là: '#342d7d'*/
15、將數(shù)字轉(zhuǎn)換為數(shù)組

/*niemvuilaptrinh.com*/const numberToArray = n => [...`${n}`].map(i => parseInt(i));numberToArray(246) /*[2, 4, 6]*/numberToArray(357911) /*[3, 5, 7, 9, 1, 1]*/
16、從 HTML 中獲取內(nèi)容

/*niemvuilaptrinh.com*/const getTextInHTML = html => (new DOMParser().parseFromString(html, 'text/html')).body.textContent || '';getTextInHTML('<h2>Hello World</h2>'); /*'Hello World'*/
17、 在 JS 中分配多個變量

/*niemvuilaptrinh.com*/var [a,b,c,d] = [1, 2, 'Hello', false];console.log(a,b,c,d) /* 1 2 'Hello' false */
18、 空數(shù)組

let arr = [1, 2, 3, 4, 5];arr.length = 0;console.log(arr); /* K?t qu? : [] */
19、 在 JS 中復制對象

/*niemvuilaptrinh.com*/const obj = {name: "niem vui lap trinh",age: 12};const copyObject = { ...obj };console.log(copyObject); /* {name: 'niem vui lap trinh', age: 12}*/
20、檢查偶數(shù)和奇數(shù)

/*niemvuilaptrinh.com*/const isEven = num => num % 2 === 0;console.log(isEven(1)); /*false*/console.log(isEven(2)); /*true*/
21、 合并兩個或多個數(shù)組 JS

/*niemvuilaptrinh.com*/const arr1 = [1, 2, 3];const arr2 = [4, 5, 6];const arr = arr1.concat(arr2);console.log(arr); /* [1, 2, 3, 4, 5, 6] */
22、 將內(nèi)容復制到剪貼板

/*niemvuilaptrinh.com*/const copyTextToClipboard = async (text) => {await navigator.clipboard.writeText(text)}
23、從一系列值中選擇一個隨機數(shù)

/*niemvuilaptrinh.com*/var max = 10;var min = 1;var numRandom = Math.floor(Math.random() * (max - min + 1)) + min;console.log(numRandom)
24、檢查元素是否聚焦

/*niemvuilaptrinh.com*/const elementFocus = (el) => (el === document.activeElement);elementIsInFocus(element);/*if true element is focus*//*if false element is not focus*/
25、用 JS 測試蘋果設備

/*niemvuilaptrinh.com*/const isAppleDevice =/Mac|iPod|iPhone|iPad/.test(navigator.platform);console.log(isAppleDevice);/*if true element is apple devices **//*if false element is not apple devices*/
26、將字符串轉(zhuǎn)換為數(shù)組

/*niemvuilaptrinh.com*/const str = "Hello";const arr = [...str];console.log(arr); /* ['H', 'e', 'l', 'l', 'o'] *
27、在 JS 中使用箭頭函數(shù)

/* regular function*/const sum = function(x, y) {return x + y;};/* arrow function */const sum = (x, y) => x + y;
28、 條件句的簡寫

學習更多技能
請點擊下方公眾號
![]()

評論
圖片
表情
