#每日一记# 用 Math 替代 if…else 写出更优雅的代码

133 阅读1分钟

老板:小张啊,我这里有一组数据,但是在页面上展示时要帮我处理一下,超过20的展示成20,小于0的展示成0。

image.png

image 2.png

小张:好的老板。

function renderData (data) {
  return data.map((item) => {
    if (item > 20) {
      return 20
    }
    else if (item < 0) {
      return 0
    }
    else {
      return item
    }
  })
}

小张一下 完成了任务。

image 3.png

这么实现肯定没有问题,但是今天介绍一个新的实现方法,就是利用 Math 对象的函数实现。

Math

通过对 Math.min 和 Math.max 函数的组合使用,就可以一行代码完成数字的处理:

function renderData (data) {
  return data.map((item) => (
    Math.max(0, Math.min(20, item))
  ))
}

封装一下:

function shrinkNumber (min, number, max) {
  return Math.max(min, Math.min(number, max))
}

常见场景

限定范围的需求通常在坐标计算中经常出现,比如子元素在拖拽时不能超过父元素的边界:

image 4.png

此时就可以利用 Math 对象来简化代码中的 if…else 结构:

function shrinkNumber (min, number, max) {
  return Math.max(min, Math.min(number, max))
}

function moveTo (child, parent) {
  return {
    top: shrinkNumber(0, child.top, parent.height - child.height),
    left: shrinkNumber(0, child.left, parent.width - child.width),
  }
}

优雅系列文章

#每日一记# 用策略模式替代 if…else 写出更优雅的代码

#每日一记# 1分钟学会如何「便利地」使用 async/await

#每日一记# 让我们优雅的扩大点击区域

#每日一记# 防止按钮在短时间内重复点击