简体   繁体   中英

Logic in for loop using JavaScript

I am having some problem when trying to perform some calculation inside a for loop using JavaScript:

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. 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.

Thanks in advance.

You have to parse the items individually before adding them together.

Using your example of

  • attributes["AGE_0_2"] is 1
  • attributes["AGE_3_4"] is 2
  • attributes["AGE_5_6"] is 3

your code

var totalYC = parseInt(attributes["AGE_0_2"] + attributes["AGE_3_4"] + attributes["AGE_5_6"]);

is probably returning 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

EDIT

Because JavaScript doesn't have typed variables it assumes that you are appending strings together.

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" . JavaScript will try to append these values together which returns "123" .

Using the ParseInt method tells JavaScript to try and parse these variables as numbers first. JavaScript is smart enough to know that the + operator is therefore a math operator and not an append.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM