首页 > 解决方案 > 如何提前停止javascript过滤功能进行优化

问题描述

const filtered = array_of_things.filter(thing => {

  const isCar = thing.item === 'car'
  const colorIsRed = thing.color === 'red'
  const isSUV = thing.type === 'SUV'
  const priceIsHigh = thing.price >= 100
  const widthIsTen = thing.width === 10

  return isCar && colorIsRed && isSUV && priceIsHigh && widthIsTen 
})

所以在我的示例代码中,即使第一次比较为假,代码也会继续执行。我如何使它以第一个错误结束并且不进行其余的比较?

这也比在每次比较时调用过滤器更好吗?具有多个过滤器,例如:

  const filter_SUV = array_of_things.filter(thing => thing.type === 'SUV')
  const filter_red = filter_SUV.filter(thing => thing.color === 'red')

标签: javascriptperformance

解决方案


不要创建单独的变量,只需将每个条件&&d 与其他条件一起返回:

const filtered = array_of_things.filter(({ item, color, type, price, width }) => (
  item === 'car' &&
  color === 'red' &&
  type === 'SUV' &&
  price >= 100 &&
  width === 10
));

是的,这种模式比调用.filter多次更有效,因为一次.filter意味着数组只迭代一次。


推荐阅读