[英]Logic in for loop using JavaScript
I am having some problem when trying to perform some calculation inside a for loop using JavaScript: 尝试使用JavaScript在for循环内执行某些计算时遇到问题:
for (var j = 0; j < count; j++) {
var attributes;
if (latlng !== 'Null') {
attributes = results[j].feature.attributes;
}
var totalYC = parseInt(attributes["AGE_0_2"] + attributes["AGE_3_4"] + attributes["AGE_5_6"]);
var r = {
pa: attributes["Planning Area Name"],
sitearea: parseFloat(attributes["SHAPE_Area"] * 0.0001),
total_pop: parseInt(attributes["TOTAL_POPULATION"]),
scpr: parseInt(attributes["TOTAL_SCPR"]),
yc: parseInt(totalYC),
age_0_2: parseInt(attributes["AGE_0_2"]),
age_3_4: parseInt(attributes["AGE_3_4"]),
age_5_6: parseInt(attributes["AGE_5_6"]),
};
r_array.push(r);
}
I want my totalYC to sum up for the total of attributes["AGE_0_2"] + attributes["AGE_3_4"] + attributes["AGE_5_6"]
just for once only. 我希望我的totalYC只能汇总一次
attributes["AGE_0_2"] + attributes["AGE_3_4"] + attributes["AGE_5_6"]
。 Let's say attributes["AGE_0_2"]
is 1, attributes["AGE_3_4"]
is 2 and attributes["AGE_5_6"]
is 3. The totalYC should be 6 but not looping thru the entire for loop and keep on plusing. 假设
attributes["AGE_0_2"]
为1, attributes["AGE_3_4"]
为2, attributes["AGE_5_6"]
为3。totalYC应该为6,但不要循环通过整个for循环并继续加。
Thanks in advance. 提前致谢。
You have to parse the items individually before adding them together. 您必须先逐项解析项目,然后再将其添加在一起。
Using your example of 用你的例子
your code 您的代码
var totalYC = parseInt(attributes["AGE_0_2"] + attributes["AGE_3_4"] + attributes["AGE_5_6"]);
is probably returning 123
可能会返回
123
If you change to 如果您更改为
var totalYC = parseInt(attributes["AGE_0_2"]) + parseInt(attributes["AGE_3_4"]) + parseInt(attributes["AGE_5_6"]);
you should now get 6
你现在应该得到
6
EDIT 编辑
Because JavaScript doesn't have typed variables it assumes that you are appending strings together. 因为JavaScript没有类型变量,所以它假定您将字符串附加在一起。
So when you type attributes["AGE_0_2"] + attributes["AGE_3_4"] + attributes["AGE_5_6"]
it is like you are saying "1" + "2" + "3"
. 因此,当您键入
attributes["AGE_0_2"] + attributes["AGE_3_4"] + attributes["AGE_5_6"]
,就像您在说"1" + "2" + "3"
。 JavaScript will try to append these values together which returns "123"
. JavaScript将尝试将这些值附加在一起,并返回
"123"
。
Using the ParseInt
method tells JavaScript to try and parse these variables as numbers first. 使用
ParseInt
方法告诉JavaScript首先尝试将这些变量解析为数字。 JavaScript is smart enough to know that the +
operator is therefore a math operator and not an append. JavaScript足够聪明,知道
+
运算符因此是数学运算符,而不是附加运算符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.