01.数组Array.prototype.map()
const arr = [1, 2, 3];
const double = x => x * 2;
arr.map(double); // [2, 4, 6]
02.数组Array.prototype.filter()
const arr = [1, 2, 3];
const isOdd = x => x % 2 === 1;
arr.filter(isOdd); // [1, 3]
03.数组Array.prototype.reduce()
const arr = [1, 2, 3];
const sum = (x, y) => x + y;
arr.reduce(sum, 0); // 6
const increment = (x, y) => [...x, x[x.length - 1] + y];
arr.reduce(increment, [0]); // [0, 1, 3, 6]
04.数组Array.prototype.find()
const arr = [1, 2, 3];
const isOdd = x => x % 2 === 1;
arr.find(isOdd); // 1
05.利用Set集合给数组去重
const removeDuplicates = (arr) => [...new Set(arr)];
console.log(removeDuplicates([1, 2, 3, 3, 4, 4, 5, 5, 6]));
// Result: [ 1, 2, 3, 4, 5, 6 ]
06.获取浏览器Cookie的值
const cookie = name => `; ${document.cookie}`.split(`; ${name}=`).pop().split(';').shift();
cookie('_ga');
// Result: "GA1.2.1929736587.1601974046"
07.颜色RGB转十六进制
const rgbToHex = (r, g, b) => "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
rgbToHex(0, 51, 255);
// Result: #0033ff
08.复制到剪贴板(此方法需要开启浏览器获取“剪贴板写入”权限)
const copyToClipboard = (text) => navigator.clipboard.writeText(text);
copyToClipboard("Hello World");
09.检查日期是否合法
const isDateValid = (...val) => !Number.isNaN(new Date(...val).valueOf());
isDateValid("December 17, 1995 03:24:00");
// Result: true
10.查找日期位于一年中的第几天
const dayOfYear = (date) =>
Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24);
dayOfYear(new Date());
// Result: 272
11.英文字符串首字母大写
const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1)
capitalize("follow for more")
// Result: Follow for more
12.计算2个日期之间相差多少天
const dayDif = (date1, date2) => Math.ceil(Math.abs(date1.getTime() - date2.getTime()) / 86400000)
dayDif(new Date("2020-10-21"), new Date("2021-10-22"))
// Result: 366
13.清除全部Cookie
const clearCookies = document.cookie.split(';').forEach(cookie => document.cookie = cookie.replace(/^ +/, '').replace(/=.*/, `=;expires=${new Date(0).toUTCString()};path=/`));
14.生成随机十六进制颜色
const randomHex = () => `#${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0")}`;
console.log(randomHex());
// Result: #92b008
15.从 URL 获取查询参数
const getParameters = (URL) => {
URL = JSON.parse(
'{"' +
decodeURI(URL.split("?")[1])
.replace(/"/g, '\\"')
.replace(/&/g, '","')
.replace(/=/g, '":"') +
'"}'
);
return JSON.stringify(URL);
};
getParameters(window.location.href);
// Result: { search : "easy", page : 3 }
更简单粗暴的如下:
Object.fromEntries(new URLSearchParams(window.location.search))
// Result: { search : "easy", page : 3 }
16.时间处理
const timeFromDate = date => date.toTimeString().slice(0, 8);
console.log(timeFromDate(new Date(2021, 0, 10, 17, 30, 0)));
// Result: "17:30:00"
17.校验数字是奇数还是偶数
const isEven = num => num % 2 === 0;
console.log(isEven(2));
// Result: True
18.求数字的平均值
const average = (...args) => args.reduce((a, b) => a + b) / args.length;
average(1, 2, 3, 4);
// Result: 2.5
19.回到顶部
const goToTop = () => window.scrollTo(0, 0);
goToTop();
20.反转字符串
const reverse = str => str.split('').reverse().join('');
reverse('hello world');
// Result: 'dlrow olleh'
21.校验数组是否为空
const isNotEmpty = arr => Array.isArray(arr) && arr.length > 0;
isNotEmpty([1, 2, 3]);
// Result: true
22.获取用户选择的文本
const getSelectedText = () => window.getSelection().toString();
getSelectedText();
23.随机打乱数组
const shuffleArray = (arr) => arr.sort(() => 0.5 - Math.random());
console.log(shuffleArray([1, 2, 3, 4]));
// Result: [ 1, 4, 3, 2 ]
24.检查用户的设备是否处于暗模式
const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
console.log(isDarkMode)
// Result: True or False
25.JavaScript中实现睡眠(同步)
const sleepSync = (ms) => {
const end = new Date().getTime() + ms;
while (new Date().getTime() < end) { /* do nothing */ }
}
const printNums = () => {
console.log(1);
sleepSync(500);
console.log(2);
console.log(3);
};
printNums();
// Result: 1, 2, 3 (2 and 3 log after 500ms)
26.JavaScript中实现睡眠(异步)
const sleepAsyn = (ms) => new Promise(resolve => setTimeout(resolve, ms));
const printNums = async() => {
console.log(1);
await sleepAsyn(500);
console.log(2);
console.log(3);
};
printNums();
// Result: 1, 2, 3 (2 and 3 log after 500ms)
Q.E.D.