gpt4 book ai didi

javascript - 如何使用 watch 函数计算对象的总和

转载 作者:行者123 更新时间:2023-11-28 15:14:36 26 4
gpt4 key购买 nike

我需要计算用户输入的对象属性的总和。我有一个带有 watch 的功能设置,但我没有得到结果。我对我所拥有的东西有兴趣。 working fiddle

 $scope.model = {}
function total() {
var totalNumber = 0;
totalNumber = totalNumber + $scope.model.minPrice + $scope.model.maxPrice + $scope.model.occup

return totalNumber;
};
$scope.$watch('model', function (newVal, oldVal) {
$scope.model.total = total();
console.log($scope.model.total)
}, true);

控制台截图

console

最佳答案

+ 运算符被重载以连接字符串。

一种选择是在添加字符串之前使用 parseInt() 将字符串转换为整数。您也可以使用逻辑 OR 运算符来处理 NaN。这只是一种方法。

totalNumber = (parseInt($scope.model.minPrice) || 0)
+ (parseInt($scope.model.maxPrice) || 0)
+ (parseInt($scope.model.occup) || 0);
console.log($scope.model);

Updated fiddle.

关于javascript - 如何使用 watch 函数计算对象的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34619092/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com