javascript - 如何提前停止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')
解决方案
不要创建单独的变量,只需将每个条件&&
d 与其他条件一起返回:
const filtered = array_of_things.filter(({ item, color, type, price, width }) => (
item === 'car' &&
color === 'red' &&
type === 'SUV' &&
price >= 100 &&
width === 10
));
是的,这种模式比调用.filter
多次更有效,因为一次.filter
意味着数组只迭代一次。
推荐阅读
- node.js - Kubernetes Node 14 pod 重新启动并以退出代码 0 终止
- java - 当以异步方式访问时,单例中的类级别变量会导致脏读吗?
- java - 使用 sharedpreferences 后计算错误
- excel - Excel VBA Vlookup 单个字符
- javascript - 承诺在 useEffect 内部未正确处理
- javascript - 将同步函数转换为异步
- c# - 我该如何优化
- php - PHP数组键的多个值
- javascript - Google Maps API 循环信息窗口
- javascript - 使用 React Context(图像编辑器应用程序)将状态从 Child 传递到 App 组件