简体   繁体   中英

Dealing with adding 'positive' and negative' values in JS

I have a custom attribute attached to elements in my DOM. This attr is being passed a value from my DB. I want to add these values together.

var value = jQuery('option:selected', id).attr('cust_attr');

If all of these values are positive numbers, everything is fine. But any negative numbers are being treated as zero. I'm using math.max to add these numbers together,

total += Math.max(0,value);

Obviously I would like the negative numbers to subtract from the total. Would anyone have any suggestions?

Math.max(0,value) gets the maximum between 0 and value. If value is negative, it will return 0. Just using total += value; should be enough.

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