美文网首页
一些 JS 代码片段(方法)

一些 JS 代码片段(方法)

作者: 越前君 | 来源:发表于2021-10-28 21:18 被阅读0次
    配图源自 Freepik

    记录一些取巧、简洁的代码片段,将会不断持续更新...

    欢迎路过的同学,补充或给出最优解,感谢...

    1. 首字母大写转换
    const captialize = ([first, ...rest]) => {
      return first.toUpperCase() + rest.join('')
    }
    
    1. 生成数字范围数组
    const range = end => {
      return Array.from({ length: end }, (_, index) => index)
    }
    
    1. 过滤数组中的虚值(falsy),包括 undefinednullfalse+0-0NaN0n''。除此之外的其他操作数被称为真值(truthy)。
    // 注意 Boolean 本身就是一个函数
    const filterFalsy = arr => arr.filter(Boolean) 
    
    1. 生成随机字符串
    const getRandomKey = () => Math.random().toString(36).slice(2)
    
    1. 生成随机十六进制颜色值(延伸)
    // 带透明的的话,取 slice(2, 10)
    const getRandomColor = () => Math.random().toString(16).slice(2, 8)
    
    1. 反转字符串
    const reverseStr = str => [...str].reduce((a, s) => s + a)
    
    1. 五星打分
    const getRating = rate => {
      if (rate > 5 || rate < 0) throw new Error('不在范围内')
      return '★★★★★☆☆☆☆☆'.substring(5 - rate, 10 - rate)
      // return '★'.repeat(rate) + '☆'.repeat(5 - rate)
    }
    

    有大佬利用这个思路做了个五星评级的组件,详看:★构建东半球最小的评级组件☆

    未完待续...

    相关文章

      网友评论

          本文标题:一些 JS 代码片段(方法)

          本文链接:https://www.haomeiwen.com/subject/wdrugltx.html