Kelvin Baumgart Kelvin Baumgart - 9 days ago 6
Javascript Question

Push Undefined syntax error JS

Need to create a program that asks the user for a value to store in an array and continues to keep asking for values to add till they have no more numbers they want to enter into the array. Afterwards I must output the array containing no zeros (Which they're allowed to enter zeros so I have to filter them out from the output) and return the sum of the array. My current issue with my program is that arr.push(x) is currently trying to push an undefined value in the function arrin. I feel as if there's a much better way of going about this then I'm currently trying so I'm all ears for improvement.

var x = parseInt(prompt("Enter a number, to exit enter NaN", "0"), 10);

var y = arrin(x);

var arr = [];

var s;

function arrin(x) {

if(x != NaN){
arr.push(x)
x = parseInt(prompt("Enter a number, to exit enter NaN", "0"), 10);
y = arrin(x);
}else{
document.write("<p>"+arr.toString()+"</p>");
s = sum(arr);
doucment.write("<p> The sum of all elements in the array is "+s+"</p>");
}
}

Answer

x != NaN will not work.

!isNaN(x) will check if the var is a number.

x != "NaN" will check if the text is literally "NaN"

either of the last two will work.

var arr = [];
var y = arrin(0);
var s;

function arrin(x) {

  if (!isNaN(x)) {
    if (x != 0) arr.push(x)
    x = parseInt(prompt("Enter a number, to exit enter NaN", "0"), 10);
    y = arrin(x);
  } else {
    document.write("<p>" + arr.toString() + "</p>");
    s = sum();
    document.write("<p> The sum of all elements in the array is " + s + "</p>");
  }
}

function sum() {
  var t = 0;
  for (var i = arr.length; i--;) t += parseInt(arr[i]);
  return t;
}