28个你应该知道的JavaScript技巧

994ab6869d8aeded7a207a88d1945de1.png

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

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

01、Javascript 反向字符串

be6c92a636cb6a308e13719e4c9eb16a.png

下面是代码:

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

02、滚动到页面顶部

7f689cbcd51e992aed2c7337f75d3641.png

下面是代码:

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

03、删除数组中的重复项

9333f3654dfa825413d3e3ff02aefffb.png

下面是代码:

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

04、 获取数组中的随机项

2c32cdff898d2f8db181df985ffff1c5.png

下面是代码:

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

05、获取数组中的最大数

4d3cf5d944bf3127ee004784e4054f1a.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、检查型号

1d05f6d4ac470d8c9e74302e33ac55f5.png

下面是代码:

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

07、检查类型为空

3a6fd58dfa058a900b079d9de42a343c.png

下面是代码:

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

08、获取数组中的最小数

de72f8ac4cdc1942d7b05f8273c5ecf9.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、获取数组中的平均数

65e57e335bfb4abcea0bb49715589752.png

下面是代码:

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

10、检查元素的类型

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

b112549859bb7e156180e20154005f99.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

d349e159aeb969e5621cff4838e38e96.png

下面是代码:

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

13、大写字符串中的字母

4e8c66e55e7f4c5bb672c6c14e86c9e8.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 转换为十六进制

2dbd22041756ae80f42d61c5eb73d89e.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、将数字转换为数组

ad8b0e52c8a83616863f275a663e8ec6.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 中获取内容

b5cca86f333f5f4e33b22b1c41dca7f6.png

下面是代码:

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

17、 在 JS 中分配多个变量

21ed7f942614a42acf1b6814e7e51721.png

下面是代码:

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

18、空数组

059ed1e05403e7dfee5f59d98cdd7a5b.png

下面是代码:

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

19、 在 JS 中复制对象

61cccaf681d4d0dd35be0c8795b0b00b.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、检查偶数和奇数

a8bb6be5f9f072a9319ecbd2aefa21eb.png

下面是代码:

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

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

8afe6433e1e03db85cdda558fc114846.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、将内容复制到剪贴板

7b36669093d054d35610ccf5d5800680.png

下面是代码:

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

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

d2191465be815b02cadb6ef647c9ffb9.png

下面是代码:

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

24、检查元素是否聚焦

3b9b3674ad012667692ed699a3cf4b1c.png

下面是代码:

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

25、用 JS 测试苹果设备

2c2a8ca2132c6f704d75f182cb0ee857.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、 将字符串转换为数组

76ba17ba43ff611e4c53a037113bb0ab.png

下面是代码:

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

27、在 JS 中使用箭头函数

7e3da2c9f483995da7f91ad118ed8de7.png

下面是代码:

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

28、条件句的简写

26323a182ff92318ceb2f70f9a704fa0.png

总结:

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

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

学习更多技能

请点击下方公众号

4256ca1f383d83cba176e5692c32594a.gif

fed7c3e53e996e4263771ed449915e54.png

4f2452b26e2b0102b095d8ce0da72644.png

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值