16 个你需要的 Javascript 代码片段
web前端开发
共 3140字,需浏览 7分钟
·
2022-05-16 01:59
const shuffleArray = (arr) => arr.sort(() => 0.5 - Math.random());console.log(shuffleArray([1, 2, 3, 4]));
// Result: [ 1, 4, 3, 2 ]
const isDateValid = (...val) => !Number.isNaN(new Date(...val).valueOf());isDateValid("December 17, 1995 03:24:00");
// Result: true
const copyToClipboard = (text) => navigator.clipboard.writeText(text);copyToClipboard("Hello World");
const dayOfYear = (date) =>
Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24);dayOfYear(new Date());
// Result: 272
const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1)capitalize("follow for more")
// Result: Follow for more
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
const clearCookies = document.cookie.split(';').forEach(cookie => document.cookie = cookie.replace(/^ +/, '').replace(/=.*/, `=;expires=${new Date(0).toUTCString()};path=/`));
const randomHex = () => `#${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0")}`;console.log(randomHex());
// Result: #92b008
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 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 timeFromDate = date => date.toTimeString().slice(0, 8);console.log(timeFromDate(new Date(2021, 0, 10, 17, 30, 0)));
// Result: "17:30:00"
const isEven = num => num % 2 === 0;console.log(isEven(2));
// Result: True
const average = (...args) => args.reduce((a, b) => a + b) / args.length;average(1, 2, 3, 4);
// Result: 2.5
const isNotEmpty = arr => Array.isArray(arr) && arr.length > 0;isNotEmpty([1, 2, 3]);
// Result: true
const getSelectedText = () => window.getSelection().toString();getSelectedText();
const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matchesconsole.log(isDarkMode)
// Result: True or False
总结 以上就是我跟你分享的16个JavaScript的实用代码片段,希望对你有所帮助,另外,如果你喜欢今天的内容,请点赞我,关注我。
最后,感谢你的阅读,祝编程愉快!
学习更多技能
请点击下方公众号
评论