28 个常见的JavaScript开发技巧

web前端开发

共 4973字,需浏览 10分钟

 · 2021-10-26

英文 | https://niemvuilaptrinh.medium.com/28-tip-javascript-you-should-know-5c8ca83e4f99

翻译 | 杨小爱


今天我将介绍一些Javascript中的常用技巧,以帮助您解决问题。
以下是在开发过程中的一些常见问题,希望能够帮助你提升开发效率。
1、 Javascript 反向字符串

以下是代码:

/*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、删除数组中的重复项

以下是代码:
/*niemvuilaptrinh.com*/const removeDuplicate = (arr) => [...new Set(arr)];removeDuplicate([1, 2, 3, 4, 4, 2, 1]); // [1, 2, 3, 4]

4、获取数组中的随机项

以下是代码:
/*niemvuilaptrinh.com*/const randomItemArray = (arr) => arr[Math.floor(Math.random() * arr.length)];randomItemArray(['a', 'b', 'c', 1, 2, 3]);

5、获取数组中的最大数

以下是代码:
/*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、获取数组中的最小数

以下是代码:
/*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、 获取数组中的平均数

以下是代码:
/*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、计算数组中元素的出现次数

以下是代码:
/*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 转换为十六进制

以下是代码:
/*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、将数字转换为数组

以下是代码:
/*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 中获取内容

以下是代码:
/*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、 空数组

以下是代码:
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、检查偶数和奇数

以下是代码:
/*niemvuilaptrinh.com*/const isEven = num => num % 2 === 0;console.log(isEven(1)); /*false*/console.log(isEven(2)); /*true*/

21、 合并两个或多个数组 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、 将内容复制到剪贴板

以下是代码:
/*niemvuilaptrinh.com*/const copyTextToClipboard = async (text) => {  await navigator.clipboard.writeText(text)}

23、从一系列值中选择一个随机数

以下是代码:
/*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、将字符串转换为数组

以下是代码:
/*niemvuilaptrinh.com*/const str = "Hello";const arr = [...str];console.log(arr); /* ['H', 'e', 'l', 'l', 'o'] *

27、在 JS 中使用箭头函数

以下是代码:
/* regular function*/const sum = function(x, y) {  return x + y;};/* arrow function */const sum = (x, y) => x + y;

28、 条件句的简写

总结
我希望这篇文章能为您提供对开发网站有用的 javascript 知识,如果您有任何问题,请在留言区给我留言。 
感谢您的支持,也感谢您的阅读,如果您觉得今天的内容对您有帮助,请记得给我点个赞。


学习更多技能

请点击下方公众号

浏览 7
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报