有意思的JavaScript 单行代码

  1. 获取浏览器Cookie的值
const cookie = name => `; ${document.cookie}`.split(`; ${name}=`).pop().split(';').shift();
    
cookie('_ga');
  1. 检查日期是否合法
const isDateValid = (...val) => !Number.isNaN(new Date(...val).valueOf());
    
isDateValid("December 17, 1995 03:24:00");
// Result: true
  1. 查找日期位于一年中的第几天
const dayOfYear = (date) =>
      Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24);
    
dayOfYear(new Date());
// Result: 272
  1. 计算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
  1. 清除全部Cookie
const clearCookies = document.cookie.split(';').forEach(cookie => document.cookie = cookie.replace(/^ +/, '').replace(/=.*/, `=;expires=${new Date(0).toUTCString()};path=/`));
  1. 从 URL 获取查询参数
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 }

或者更为简单的:

Object.fromEntries(new URLSearchParams(window.location.search))
// Result: { search : "easy", page : 3 }
  1. 校验数字是奇数还是偶数
const isEven = num => num % 2 === 0;
    
console.log(isEven(2)); 
// Result: True
  1. 求数字的平均值
const average = (...args) => args.reduce((a, b) => a + b) / args.length;
    
average(1, 2, 3, 4);
// Result: 2.5
  1. 校验数组是否为空
const isNotEmpty = arr => Array.isArray(arr) && arr.length > 0;
    
isNotEmpty([1, 2, 3]);
// Result: true
  1. 打乱数组
const shuffleArray = (arr) => arr.sort(() => 0.5 - Math.random());
    
console.log(shuffleArray([1, 2, 3, 4]));
// Result: [ 1, 4, 3, 2 ]

11.获取年月日时分秒

let date = new Date()
let str = date.getFullYear() + '-' + (date.getMonth() + 1) +  '-' +  date.getDate() + ' ' + date.toTimeString().slice(0, 8)
// '2021-12-1 10:53:47'

来源:https://mp.weixin.qq.com/s/HMMi_mGIX1Lptcpgf5pXxg

你可能感兴趣的:(有意思的JavaScript 单行代码)