JS奇巧淫技大杂烩(更新中)⏲👇

12,062 阅读2分钟

本文的目的

  • 😃 如何让你的代码看起来更优雅
  • 🥰 让代码可读性更高,看起来更直观
  • 👍 避免无用的代码,减少代码量
  • 🐂🔥 当你的同事看到你的代码时很哇塞,直呼内行

使用&&替代if

const doSometings = () => {}

const isTrue = true
let temp = ''
if(isTrue){
    doSometings()
    temp = 'isTrue'
}

// 替代方案
isTrue && this.doSometings()
isTrue && (temp = 'isTrue')

switch替代if

const temp = 1

if(temp === 1){
    // ...
}
if(temp === 2){
    // ...
}

// 替代方案
switch(true){
    case temp === 1:
        // ...
        break;
    case temp === 2:
        // ...
        break;
    default:
        // ...
        break;
}

[] or {} => null (永远不要相信后端返回的数据)

const { data } = await getApiData()

// 如果data类型是一个数组
console.log(data[0]) // 如果data返回了个null,会报错

// 如果data类型是一个对象
console.log(data.a) // 如果data返回了个null,会报错

// 可以写成下面这样
console.log((data || [])[0])
console.log((data || {}).a)
// 此时就算data返回了null,也只会提示undefined,并不会报错阻塞代码

生成长度为N的数组

// 生成长度为100的数组
const arrN = [...Array(100).keys()]
// [0,1,2,3,...,99]

生成A-Z的数组

const AZCodeArr = [...Array(91).keys()].filter(i => i > 64).map(i => String.fromCharCode(i))
//['A','B','C','D'...]

取最后一位数字

const num = 12345
const num2 = '54321'
console.log(num%10) // 5
console.log(num2%10) // 1 当然隐式转换也是可以的

取整

const num = 123.456
console.log(num | 0) // 123

写一个中间件管理你的工具类

image.png

// index.js

[
  'utilA',
  'utilB'
].forEach(m => {
  Object.assign(exports, require(`./lib/${m}`))
})

exports.lodash = require('lodash')


// 外部引用
const { utilA, utilB, lodash : _ } = require('utils')

万能reduce

累加

const arr = [
    {num:1},
    {num:2},
    {num:3}
]
console.log(arr.reduce((p,n) => p + n.num, 0)) // 6

去重

// 去除id重复的对象
const arr = [
    {
        id:'1',
        msg:''
    },
    {
        id:'2',
        msg:''
    },
    {
        id:'1',
        msg:''
    }
]
console.log(arr.reduce((p,n) => {
    if(!p.find(i => i.id === n.id)) p.push(n)
    return p
},[])) // [{id:'1',msg:''},{id:'2',msg:''}]

结尾

本文会一直更新!

⏲⏲⏲ 更新时间:2021-12-15

👍👍👍 觉得有用的可以收藏使用!!!

❤️❤️❤️ 感谢阅读,小伙伴们觉得不错的点个赞!!!