9个为初学开发者准备 JavaScript 单行代码
web前端开发
共 2600字,需浏览 6分钟
·
2022-10-15 00:58
英文 | https://medium.com/dailyjs/nine-javascript-one-liners-for-the-beginner-2021-developer-792872ad6137
const shuffleArray = (arr) => arr.slice().sort(() => Math.random() - 0.5)
console.log(shuffleArray([1, 2, 3, 4, 5, 6]))
// Result: [6, 2, 3, 1, 5, 4]
const throwdice = () => ~~(Math.random() * 6) + 1;
// Examples
throwdice(); // Result: 4
throwdice(); // Result: 1
throwdice(); // Result: 6
const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
// Result: True or False
const isBrowser = typeof window === 'object' && typeof document === 'object';
// Result: True or False
const cookie = name => `; ${document.cookie}`.split(`; ${name}=`).pop().split(';').shift();
cookie('_ga');
// Result: GA1.2.821239271.5181504719
cookie('lang');
// Result: "en"
const pastSevenDays = [...Array(7).keys()].map(days => new Date(Date.now() - 86400000 * days));
console.log(pastSevenDays);
// Result: [Array with 7 Date Objects]
const comingSevenDays = [...Array(7).keys()].map(days => new Date(Date.now() + 86400000 * days));
console.log(comingSevenDays);
// Result: [Array with 7 Date Objects]
let a = 1
let b = 2
[a, b] = [b, a];
console.log(a)
// Result: 2
console.log(b)
// Result: 1
const slugify = string => string.toLowerCase().replace(/\s+/g, '-').replace(/[^\w-]+/g, '');
// Example
slugify('Episode IV: A New Hope');
// Result:'episode-iv-a-new-hope
const randomHexColor = () => '#' + (0x1000000 + Math.random() * 0xffffff).toString(16).slice(1, 6);
randomHexColor() // Result: #fec150
randomHexColor() // Result: #abba22
randomHexColor() // Result: #304060
学习更多技能
请点击下方公众号
评论