Javascript AngularJS-计算对象属性时出现奇怪错误
我有这个计算Javascript AngularJS-计算对象属性时出现奇怪错误,javascript,angularjs,Javascript,Angularjs,我有这个计算 if (typeof $scope.memoryTable[name][category]['total'] !== 'undefined') { $scope.memoryTable[name][category]['total'] = $scope.memoryTable[name][category]['total']; } else { $scope.memoryTable[name][category]['total'] = 0; } 这看起来很正常,显
if (typeof $scope.memoryTable[name][category]['total'] !== 'undefined') {
$scope.memoryTable[name][category]['total'] = $scope.memoryTable[name][category]['total'];
}
else {
$scope.memoryTable[name][category]['total'] = 0;
}
这看起来很正常,显然没有错误
但是,如果我尝试对该属性进行简单计算,即
if (typeof $scope.memoryTable[name][category]['total'] !== 'undefined') {
// add 10
$scope.memoryTable[name][category]['total'] = $scope.memoryTable[name][category]['total'] + 10;
}
else {
$scope.memoryTable[name][category]['total'] = 0;
}
然后AngularJS抛出了一堆我不知道是什么意思的错误(见截图)
此外,尽管存在错误,它仍会进行计算,但值不正确(将返回大约几千)
这里潜在的问题是什么?我认为这可能与消化周期有关
使用$log API检查total属性的数据类型,并继续检查其他属性,如下所示:
if ($scope.memoryTable &&
$scope.memoryTable[name] &&
$scope.memoryTable[name][category] &&
$scope.memoryTable[name][category]['total'] &&
typeof $scope.memoryTable[name][category]['total'] !== 'undefined') {
// check the type of total
$log.log("type of the total" + typeof $scope.memoryTable[name][category]['total']);
// add 10
$scope.memoryTable[name][category]['total'] += 10;
}
else {
$scope.memoryTable[name][category]['total'] = 0;
}
// Check the value
$log.log("value of the total" + $scope.memoryTable[name][category]['total']);
看起来$scope.memoryTable或…['total']在$watch的某处。所以在$digest循环之间,您需要再次尝试修改它 var total=$scope.memoryTable[name][category]['total'] 如果(总数的类型!=“未定义”){ }否则{
total = 0;
}
$scope.memoryTable[name][category][total']=total 哪个值包含
$scope.memoryTable[name][category]['total']
,然后再对其进行任何操作?是的,听起来像,但仍然有错误。将新值赋给$scope.memoryTable[name][category][total']
也会触碰它,这会扭曲$digest循环?首先在if条件之前检查total的值和类型。
total = 0;