分享 28 个你应该知道的JS 实用小技巧

4880c00bd5664f8b6f717581719de256.png

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

今天我将分享一些Javascript中的常用技巧,以帮助您解决问题。设置过程中的常见问题更快更容易。

01、Javascript 反向字符串

15d0eb8b2747980323b9cb2f89d3c093.png

下面是代码:

/*niemvuilaptrinh.com*/
const stringReverse = str => str.split("").reverse().join("");
stringReverse('hello world'); /*dlrow olleh*/

02、滚动到页面顶部

3d02d9c32e17c37fd99a86c4ab761378.png

下面是代码:

/*niemvuilaptrinh.com*/
const scrollToTop = () => window.scrollTo(0, 0);
scrollToTop();

03、删除数组中的重复项

c55512426bfa6c1a4f17b985ded4562c.png

下面是代码:

/*niemvuilaptrinh.com*/
const removeDuplicate = (arr) => [...new Set(arr)];
removeDuplicate([1, 2, 3, 4, 4, 2, 1]); // [1, 2, 3, 4]

04、 获取数组中的随机项

1971d813c06711e332300b1d517fb4ee.png

下面是代码:

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

05、获取数组中的最大数

d1040133e6f5949df43110cdaeac4ff8.png

下面是代码:

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

06、检查型号

03402ce941c408452e5c7ac4cee0a428.png

下面是代码:

/*niemvuilaptrinh.com*/
function isNumber(num) {
  return !isNaN(parseFloat(num)) && isFinite(num);
}
isNumber("Hello"); /*false*/
isNumber(123);/*true*/

07、检查类型为空

40e7629905b2a73cfd253fac62e43038.png

下面是代码:

/*niemvuilaptrinh.com*/
const checkNull = val => val === undefined || val === null;
checkNull(123) /* false */
checkNull() /* true */
checkNull('hello') /* false */

08、获取数组中的最小数

87141b1031d7aa025503af8d0174a689.png

下面是代码:

/*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*/

09、获取数组中的平均数

8dbc572c2fa479fe0438b58db0849bca.png

下面是代码:

/*niemvuilaptrinh.com*/
const averageNumber = arr => arr.reduce((a, b) => a + b) / arr.length;
averageNumber([1, 2, 3, 4, 5]) /* 3 */

10、检查元素的类型

2b7ef7cbfa6e0d5fa8071541435a5802.png

下面是代码:

/*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、 计算数组中元素的出现次数

6c5115f2e9d47baa1243c71469b5b130.png

下面是代码:

/*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

533b72066ec44b95708098c1cd852bd7.png

下面是代码:

/*niemvuilaptrinh.com*/
const getCurrentURL = () => window.location.href;
getCurrentURL() /* https://www.niemvuilaptrinh.com */

13、大写字符串中的字母

727dcb4c03470b09fd2765dc512a7516.png

下面是代码:

/*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 转换为十六进制

c4712469f14b4022c8285f4bd8270b6d.png

下面是代码:

/*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、将数字转换为数组

5a8e6721811190f34ffa833ccc08b3fb.png

下面是代码:

/*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 中获取内容

93debbbef8cc2c3582d05e50843dc2f1.png

下面是代码:

/*niemvuilaptrinh.com*/
const getTextInHTML = html => (new DOMParser().parseFromString(html, 'text/html')).body.textContent || '';
getTextInHTML('<h2>Hello World</h2>'); /*'Hello World'*/

17、 在 JS 中分配多个变量

696e61700c45392a2f0643cfeb936c29.png

下面是代码:

/*niemvuilaptrinh.com*/
var [a,b,c,d] = [1, 2, 'Hello', false];
console.log(a,b,c,d) /* 1 2 'Hello' false */

18、空数组

99b6df8dc5db5e72b7c40cf78f4ee6b8.png

下面是代码:

let arr = [1, 2, 3, 4, 5];
arr.length = 0;
console.log(arr); /* Kết quả : [] */

19、 在 JS 中复制对象

66eb47005b60f3f530f8766705f23b21.png

下面是代码:

/*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、检查偶数和奇数

b69da0e707741659e272745aba945356.png

下面是代码:

/*niemvuilaptrinh.com*/
const isEven = num => num % 2 === 0;
console.log(isEven(1)); /*false*/
console.log(isEven(2)); /*true*/

21、合并两个或多个数组 JS

30ee06f9a05f34c25c36f3b83ff3edbb.png

下面是代码:

/*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、将内容复制到剪贴板

9f8d2e1d114be570dff5af0db6e78fc2.png

下面是代码:

/*niemvuilaptrinh.com*/
const copyTextToClipboard = async (text) => {
  await navigator.clipboard.writeText(text)
}

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

fe02abcf1dedfcb995a7bad3288a2c9b.png

下面是代码:

/*niemvuilaptrinh.com*/
var max = 10;
var min = 1;
var numRandom = Math.floor(Math.random() * (max - min + 1)) + min;
console.log(numRandom)

24、检查元素是否聚焦

85da78948d0233b0dbef4f4651b261fa.png

下面是代码:

/*niemvuilaptrinh.com*/
const elementFocus = (el) => (el === document.activeElement);
elementIsInFocus(element);
/*if true element is focus*/
/*if false element is not focus*/

25、用 JS 测试苹果设备

7b4c0eeeae86d0720d7ae1ebed4724e7.png

下面是代码:

/*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、 将字符串转换为数组

b70ce7ef3980e5d0719cd5d529b1cedc.png

下面是代码:

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

27、在 JS 中使用箭头函数

0124790771bff65235ec668555163c4d.png

下面是代码:

/* regular function*/
const sum = function(x, y) {
  return x + y;
};
/* arrow function */
const sum = (x, y) => x + y;

28、条件句的简写

97f8a53b5569c82ea440cc7b57a1c85c.png

总结:

我希望这篇文章能为您提供对开发网站有用的javascript知识,如果您有任何问题,请留言区给我留言,我会尽快回复。

感谢您的阅读,祝您今天过得愉快!

学习更多技能

请点击下方公众号

07385f9c82a7b2aa9083ceee27109ae7.gif

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值