简体   繁体   中英

Sum not being displayed in function

I am trying to return a sum from an array and for some reason it's not displaying. I tried various things but for some reason it's not returning the sum of the array. When I call tableSum(sum) from the console, it returns it, but it's not happening in the JavaScript.

Here is my code:

var tableSum = function () {
    'use strict';
    var sum = 0,
        i;
    for (i = 0; i < numberArray.length; i += 1) {
        sum += numberArray[i];
    }
    return sum;
    document.getElementById('sum').innerHTML = sum;
};

HTML:

<table border="1">
    <tr>
        <td style = "text-align:right;">Sum:</td>
        <td style="width:100px" id = "sum">&#160;</td>
    </tr>

The return statement exits the function and prevents the execution of the line below it where you attempt to assign the results to the DOM element. From Mozilla's documentation :

A function immediately stops at the point where return is called.

Try the following instead:

var tableSum = function () {
    'use strict';
    var sum = 0, i;
    for (i = 0; i < numberArray.length; i += 1) {
        sum += numberArray[i];  
    }

    return sum;
};

document.getElementById('sum').innerHTML = tableSum();

Separating the rendering from your function makes it more flexible and reusable, and will allow you to use the same function to update other DOM elements for example.

It looks like you're returning from the function before you update the DOM.

Try moving the return statement to after the DOM manipulation:

document.getElementById('sum').innerHTML = sum;
return sum;

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