Need to convert result of [removed] to number on javascript

后端 未结 2 624
难免孤独
难免孤独 2021-02-10 11:07

I have a html that contains tables like the following example


    

        
相关标签:
2条回答
  • 2021-02-10 11:24

    Try something like this, using a more functional approach:

    var sum = [].map.call(valuelements, function(v) {
      return +v.textContent; }).reduce(function(a, b) { return a + b; });
    
    0 讨论(0)
  • 2021-02-10 11:34

    You need to initialize counter with a starting number, otherwise you're performing math on undefined.

    var counter = 0;
    

    And then in the loop, use parseInt, parseFloat, or a direct number conversion on the .innerHTML value.

    var counter = 0;
    
    for (var i=0; i<features.length; i++){ 
      counter += parseFloat(valuelements[i].innerHTML);
    }
    

    In a modern browser, you could do this:

    var count = [].reduce.call(valueelements, function(c, v) {
        return c + parseFloat(v.innerHTML);
    }, 0);
    
    0 讨论(0)
提交回复
热议问题