问题描述
我有一个包含多个对象的对象.每个对象都有一个高度和宽度,我需要将它们加在一起以获得总的高度和宽度.我需要根据用户输入更新总数.
I have an object which contains multiple objects. Each object has a height and a width, which I need to add together to get a total height and width. I need to update the totals on input from the user.
对象:
$scope.myObj = {
wall1: {
wFeet: 0,
wInches: 0,
hFeet: 0,
hInches: 0,
totalWidth: 0,
totalHeight: 0
},
wall2: {
wFeet: 0,
wInches: 0,
hFeet: 0,
hInches: 0,
totalWidth: 0,
totalHeight: 0
},
wall3: {
wFeet: 0,
wInches: 0,
hFeet: 0,
hInches: 0,
totalWidth: 0,
totalHeight: 0
}
};
现在,我有了一个函数,可以获取英尺和英寸的值,将其转换为十进制英尺,然后将它们加起来以得出每面墙的总宽度和高度.
Right Now I have a function that takes the feet and inches values, converts to decimal feet and adds them up to give the total width and height for each wall.
$scope.setTotalWidthAndHeight = function() {
angular.forEach($scope.walls, function(wall) {
//first convert inches to decimal of ft
angular.forEach(wall, function(dim, dimKey) {
if(dimKey === 'wInches') {
wall.wallWidth = wall.wFeet + (0.0833 * dim);
}
if(dimKey === 'hInches') {
wall.wallHeight = wall.hFeet + (0.0833 * dim);
}
})
});
};
我现在遇到的问题是将每个对象的所有 totalWidth
和 totalHeight
值相加,以获得所有墙的最终宽度和高度.必须有比下面更好的方法.
What's Im having a problem with now is adding up all the totalWidth
and totalHeight
values from each object to get one final width and height for all walls combines. There has to be a better way to do it than below.
例如:
var allTotalWidths = $scope.myObj.wall1.totalWidth + $scope.myObj.wall2.totalWidth + $scope.myObj.wall3.totalWidth;
推荐答案
您的函数可以进行一些优化,我将假设您当前在 wall.wallWidth =
和 wall.wallHeight =
,因为您的示例数据中不存在先前的属性,所以您本打算具有 wall.totalWidth =
和 wall.totalHeight =
可能会引发错误.
Your function can be optimised a little and I'm going to assume where you've currently got wall.wallWidth =
and wall.wallHeight =
you meant to have wall.totalWidth =
and wall.totalHeight =
as the previous properties don't exist in your example data and will have likely thrown an error.
var totalWidths = 0,
totalHeights = 0;
$scope.setTotalWidthAndHeight = function()
{
angular.forEach($scope.walls, function(wall)
{
wall.totalWidth = wall.wFeet + (0.0833 * wall.wInches);
wall.totalHeight = wall.hFeet + (0.0833 * wall.hInches);
totalWidths += wall.totalWidth;
totalHeights += wall.totalHeight;
});
};
我更改了您的功能,一次完成了所有总计.它将填充初始对象的 totalWidth/Height
属性,并在 totalWidths
和 totalHeights
变量中保留所有宽度和高度的连续总计
I've altered your function to do all the totalling in one swoop. It will populate the totalWidth/Height
properties of your initial object and also keep a running total of all widths and heights in the totalWidths
and totalHeights
variables.
这篇关于嵌套对象的值相加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!