如何为JS parseFloat求和逻辑添加published状态过滤条件?
没问题,这其实很简单,只需要在你的forEach回调里加个条件判断就行,我给你两种实现方式,你可以根据自己的需求选择:
方式一:贴合你现有代码框架的修改
这种方式保持你原来三次遍历的结构,只在对应循环里添加过滤条件:
// 重要:先初始化统计值为0,避免出现NaN的情况 $scope.countOffers.offersTotal.total = 0; $scope.countOffers.offersActive.total = 0; $scope.countOffers.offersDeactivated.total = 0; $scope.getTotalOffers = response.data.offers; // 统计所有offer总和(原逻辑不变) $scope.getTotalOffers.forEach(function (offer) { $scope.countOffers.offersTotal.total += parseFloat(offer.addOffers); }); // 仅统计published=true的offer总和 $scope.getTotalOffers.forEach(function (offer) { if (offer.published === true) { $scope.countOffers.offersActive.total += parseFloat(offer.addOffers); } }); // 仅统计published=false的offer总和 $scope.getTotalOffers.forEach(function (offer) { if (offer.published === false) { $scope.countOffers.offersDeactivated.total += parseFloat(offer.addOffers); } });
方式二:更高效的单次遍历优化
上面的写法要遍历三次数组,当offer数量较多时会浪费性能,推荐改成一次遍历完成所有统计:
// 初始化统计值为0 $scope.countOffers.offersTotal.total = 0; $scope.countOffers.offersActive.total = 0; $scope.countOffers.offersDeactivated.total = 0; $scope.getTotalOffers = response.data.offers; // 一次遍历完成三个统计逻辑 $scope.getTotalOffers.forEach(function (offer) { // 先把字符串转成数字,避免重复计算 const offerCount = parseFloat(offer.addOffers); // 累加总数 $scope.countOffers.offersTotal.total += offerCount; // 根据published值分情况累加 if (offer.published === true) { $scope.countOffers.offersActive.total += offerCount; } else if (offer.published === false) { $scope.countOffers.offersDeactivated.total += offerCount; } });
额外注意点
如果你的published字段在数据库里存储的是字符串类型(比如"TRUE"/"FALSE"),记得把判断条件改成对应的字符串匹配,比如offer.published === "TRUE"。
内容的提问来源于stack exchange,提问作者Jordan Ryan Madeley
相关产品推荐
相关产品推荐

