9个为初学开发者准备 JavaScript 单行代码

英文 | 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;// Examplesthrowdice(); // Result: 4throwdice(); // Result: 1throwdice(); // 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.5181504719cookie('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 = 1let b = 2[a, b] = [b, a];console.log(a)// Result: 2console.log(b)// Result: 1

const slugify = string => string.toLowerCase().replace(/\s+/g, '-').replace(/[^\w-]+/g, '');// Exampleslugify('Episode IV: A New Hope');// Result:'episode-iv-a-new-hope

const randomHexColor = () => '#' + (0x1000000 + Math.random() * 0xffffff).toString(16).slice(1, 6);randomHexColor() // Result: #fec150randomHexColor() // Result: #abba22randomHexColor() // Result: #304060
学习更多技能
请点击下方公众号
![]()

评论
