0

I am a newbie to Javascript and trying my hands on it.

I wrote 2 functions.

The 1st function returns an array of digits and 2nd one loops through it and sums up the array but instead of that, it returns me the first item of an array only. Why ?

function addWorth()
    { 


        var table1= document.getElementById("tableNetWorths");

        var rowCount1= table1.rows.length;

        //var row1= table1.insertRow(rowCount1);


        var arr= [];


       for(var count = 0; count < rowCount1; count++)
       {    
            arr.push(table1.rows[count].cells[1].innerHTML);          
       }


       arr.shift();
       return arr;

    } 

    function showWorthSum()
    {
        var returnedArr= [];

        returnedArr.push(addWorth());

         totalWorth= 0;

        var arrCount= returnedArr.length;

        for(var count = 0; count < arrCount; count++)
        {    
             totalWorth= parseInt(totalWorth)+ parseInt(returnedArr[count]); 

        }

        return parseInt(totalWorth);
    }

button:

 <button class="btn btn-primary" onclick="document.write(showWorthSum())" type="button">Show Sum</button>

array:

100,200,344,22,122,99

4
  • Can you show some of your table HTML ? Commented Jun 9, 2017 at 21:25
  • 1
    @Covert I think what you want is var returnedArr = addWorth() Commented Jun 9, 2017 at 21:26
  • @hack3rfx thanks but I didn't get the reason behind it? Why would an array variable fail? Commented Jun 9, 2017 at 21:27
  • 1
    @Covert your addWorth function is returning an array. You were adding that array, to another array. What you want to do, is assign it, not "push" it. Commented Jun 9, 2017 at 21:28

1 Answer 1

3

This should fix the issue:

var returnedArr = addWorth();
Sign up to request clarification or add additional context in comments.

7 Comments

[[100,200,344,...]] vs [100,200,344,...]
If you push, you will have an array with one element. The element itself will have a value of the return array. And you do not need that as you loop the return array elements.
It would be more helpful if you put a more extensive explanation into your answer.
@SamAxe but still [[100,200,344,...]] it has my elements in it, it should have added or had shown none, why would it show me 100 only ?
If you still want to push then var arrCount= returnedArr[0].length; and parseInt(returnedArr[0][count])
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.