• JavaScript 单行功能代码


    1、生成随机字符串

    const randomString = () => Math.random().toString(36).slice(2)
    randomString() // gi1qtdego0b
    randomString() // f3qixv40mot
    randomString() // eeelv1pm3ja
    

    2、转义HTML特殊字符

    const escape = (str) => str.replace(/[&<>"']/g, (m) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[m]))
    escape('<div class="medium">Hi Medium.</div>') 
    // &lt;div class=&quot;medium&quot;&gt;Hi Medium.&lt;/div&gt
    

    3、字符串中每个单词的第一个字符大写

    const uppercaseWords = (str) => str.replace(/^(.)|\s+(.)/g, (c) => c.toUpperCase())
    uppercaseWords('hello world'); // 'Hello World'
    

    4、将字符串转换为camelCase

    const toCamelCase = (str) => str.trim().replace(/[-_\s]+(.)?/g, (_, c) => (c ? c.toUpperCase() : ''));
    toCamelCase('background-color'); // backgroundColor
    toCamelCase('-webkit-scrollbar-thumb'); // WebkitScrollbarThumb
    toCamelCase('_hello_world'); // HelloWorld
    toCamelCase('hello_world'); // helloWorld
    

    5、数组去重

    const removeDuplicates = (arr) => [...new Set(arr)]
    console.log(removeDuplicates([1, 2, 2, 3, 3, 4, 4, 5, 5, 6])) 
    // [1, 2, 3, 4, 5, 6]
    

    6、展平一个数组

    const flat = (arr) =>
        [].concat.apply(
            [],
            arr.map((a) => (Array.isArray(a) ? flat(a) : a))
        )
    // Or
    const flat = (arr) => arr.reduce((a, b) => (Array.isArray(b) ? [...a, ...flat(b)] : [...a, b]), [])
    flat(['cat', ['lion', 'tiger']]) // ['cat', 'lion', 'tiger']
    

    7、从数组中删除虚假值

    const removeFalsy = (arr) => arr.filter(Boolean)
    removeFalsy([0, 'a string', '', NaN, true, 5, undefined, 'another string', false])
    // ['a string', true, 5, 'another string']
    

    8、检查一个数字是偶数还是奇数

    const isEven = num => num % 2 === 0
    isEven(2) // true
    isEven(1) // false
    

    9、获取参数的平均值

    const average = (...args) => args.reduce((a, b) => a + b) / args.length;
    average(1, 2, 3, 4, 5);   // 3

    10、将数字截断为固定小数点

    const round = (n, d) => Number(Math.round(n + "e" + d) + "e-" + d)
    round(1.005, 2) //1.01
    round(1.555, 2) //1.56
    

    11、计算两个日期相差天数

    const diffDays = (date, otherDate) => Math.ceil(Math.abs(date - otherDate) / (1000 * 60 * 60 * 24));
    diffDays(new Date("2021-11-3"), new Date("2022-2-1"))  // 90
    

    12、将RGB颜色转换为十六进制

    const rgbToHex = (r, g, b) => "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1)
    rgbToHex(255, 255, 255)  // '#ffffff'
    

    13、检测暗模式

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

    14、暂停一会

    const pause = (millis) => new Promise(resolve => setTimeout(resolve, millis))
    const fn = async () => {
      await pause(1000)
      console.log('fatfish') // 1s later
    }
    fn()
    

      

  • 相关阅读:
    java中的 equals 与 ==
    String类的内存分配
    SVN用命令行更换本地副本IP地址
    npoi 设置单元格格式
    net core 微服务框架 Viper 调用链路追踪
    打不死的小强 .net core 微服务 快速开发框架 Viper 限流
    net core 微服务 快速开发框架 Viper 初体验20201017
    Anno 框架 增加缓存、限流策略、事件总线、支持 thrift grpc 作为底层传输
    net core 微服务 快速开发框架
    Viper 微服务框架 编写一个hello world 插件02
  • 原文地址:https://www.cnblogs.com/bomdeyada/p/16106902.html
Copyright © 2020-2023  润新知