0

This works fine if I sum numbers in JavaScript in an Array. But when I ask their input from User then they are printed as if the numbers are in string. Kindly help me in finding the flaw in my code.

var tArr = [];

for(var f = 1;f<=4;f++)                                                           
{   
    // tArr.push(f);  
    var z = prompt("Enter numbers for Sum");   
    tArr.push(z);                              

}   
var r = parseInt(tArr);   
alert(tArr);       

var summ = 0;      
for(var w = 0; w< tArr.length; w++)     
{   
    summ += tArr[w];   
}   
console.log(summ);

2 Answers 2

2

To convert all values to number just do +tArr[w] then sum it. The +tArr[w] will coerce each value into a number instead of a string and hence will sum it instead of concatenating it.

var tArr = [];

for(var f = 1;f<=4;f++)                                                           
{   
    // tArr.push(f);
    var z = prompt("Enter numbers for Sum");   
    tArr.push(z);                              

}   
//var r = parseInt(tArr); This line is not doing anything.
alert(tArr);       

var summ = 0;      
for(var w = 0; w< tArr.length; w++)     
{   
    summ += +tArr[w];   
}   
console.log(summ);

Sign up to request clarification or add additional context in comments.

3 Comments

But why are they being taken as strings?
Because window.prompt() returns a string, which is added to the array tArr. While iterating the strings are converted to number by adding a + before it. developer.mozilla.org/en-US/docs/Web/API/Window/prompt
Ohkay..! Thanks alot Amardeep!
0

var sum=0;
var len=(Number(prompt("Enter len of array")));
var ar=new Array();

for(var i=0;i<len;i++){
  ar.push(Number(prompt("Enter array elements:"+ar[i])));
}
for(var i=0;i<len;i++){
  sum+=ar[i];
}

document.write(sum+" ");

Comments

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.