比较简短实用的javascript代码

203 阅读2分钟

获取浏览器的cookie值

用document.cookie获取

const getcookie = name => `; ${document.cookie}`.split(`; ${name}=`).pop().split(';').shift();

getcookie('_ga');

// Result: "GA1.2.1929736587.1601974046"

清除所有cookie

const clearCookies = document.cookie.split(';').forEach(cookie => document.cookie = cookie.replace(/^ +/, '').replace(/=.\*/, `=;expires=${new Date(0).toUTCString()};path=/`));

求平均值

使用reduce

const average = (...args) => args.reduce((a, b) => a + b) / args.length;

average(1, 2, 3, 4);

// Result: 2.5

将rgba转为十六进制

const rgbToHex = (r, g, b) =>

"#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);


rgbToHex(0, 51, 255);

// Result: #0033ff`

找出一年中的某一天

  • Math.floor()向下取整
  • getFullYear()* 方法返回指定日期的年份(1000 年到 9999 年之间的日期的四位数字)
const dayOfYear = (date) =>

Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24);


dayOfYear(new Date());

// Result: 272

检查日期是否有效

const isDateValid = (...val) => !Number.isNaN(new Date(...val).valueOf());


isDateValid("December 17, 1995 03:24:00");

// Result: true

计算两天之间相差的天数

const dayDif = (date1, date2) => Math.ceil(Math.abs(date1.getTime() - date2.getTime()) / 86400000)



dayDif(new Date("2021-02-08"), new Date("2022-02-08"))

// Result: 365

将字符串首字母大写

const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1)


capitalize("follow for more")

// Result: Follow for more

翻转字符串

const reverse = str => str.split('').reverse().join('');

reverse('hello world');

// Result: 'dlrow olleh'

数组区重

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 ]

检查数组是否为空

const isEmpty = arr => Array.isArray(arr) && arr.length > 0;

isEmpty([1, 2, 3]);

// Result: true

打乱数组

使用 sort() 和 random() 方法对数组进行打乱混合。

const shuffleArray = (arr) => arr.sort(() => 0.5 - Math.random());

console.log(shuffleArray([1, 2, 3, 4]));

// Result: [ 1, 4, 3, 2 ]

从url获取查询参数

通过 window.location 或原始 URL 轻松查询 juejin.com?search=easy&page=3 的参数

const getParameters = (URL) => {

URL = JSON.parse('{"' + decodeURI(URL.split("?")[1]).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"') +'"}');

return JSON.stringify(URL);

};

getParameters(window.location)

// Result: { search : "easy", page : 3 }

或则

const urlParams = new URLSearchParams(window.location.search)

获取用户选定的文本

使用内置getSelection属性获取用户选择的文本。

const getSelectedText = () => window.getSelection().toString();

getSelectedText();

检测用户是否处于暗模式

const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches

console.log(isDarkMode) // Result: True or False

回到顶部

使用 window.scrollTo(0, 0) 方法自动回到顶部。将 x 和 y 都设置为 0。

const goToTop = () => window.scrollTo(0, 0);

goToTop();

确认奇偶数

const isEven = num => num % 2 === 0;

console.log(isEven(2));

// Result: True

从日期获取“时分秒”格式的时间

const timeFromDate = date => date.toTimeString().slice(0, 8);

console.log(timeFromDate(new Date(2021, 0, 10, 17, 30, 0)));

// Result: "17:30:00"

复制到粘贴板

使用 navigator.clipboard.writeText 轻松将任何文本复制到剪贴板上。

const copyToClipboard = (text) => navigator.clipboard.writeText(text);

copyToClipboard("Hello World");