开发思维小技巧

264 阅读1分钟

背景

撸码过程中总会遇到非常多的场景,有用黑科技解决的,也有用“奇淫技巧”处理的,开贴记录总结一下自己遇到的有意思的方法

一、快速获取数组中最接近的数

获取比自己小的数

const sizeList = [250, 16, 24, 570, 30, 32, 36, 40, 48, 50, 60, 20,64];

function getValue(size) {
  return (
    size -
    sizeList.reduce(function (closest, v) {
      return size >= v ? Math.min(size - v, closest) : closest;
    }, 1e100)
  );
}

getValue(20) // 16

获取比自己大的数

function getValue(size) {
  return (
    size +
    sizeList.reduce(function (closest, v) {
      return size <= v ? Math.min(v - size, closest) : closest;
    }, 1e100)
  );
}

getValue(20) // 24

二、可选链以及感叹号使用

可选链

    let a = {name: '益达', profile: {age: '18'}}
    a?.profile?.name?.test // 可选链:'?.':类似于lodash的safeGet, 如果有后续属性才去取对应key  

双问号用法

如果a?.profile?.age 不存在,则返回100,那么 ?? 和 || 有什么区别?

||如果前面条件为0/false,则都会返回后面的。 ??只有当前者为null和undefined,才返回后者。

    const value = a?.profile?.age ?? 100 // 18

ts中感叹号的巧用

    let a = {name: '益达', profile: {age: '18'}}
    a!.profile!.age // 确认函数链条, !.表示对应属性一定存在
    funtion test(){
        // ts中表示
        return name!; // 表示name一定不为null/undefined
    }