I’m working through a fundamentals course on JavaScript. I was given this assignment on arrays:
"Using a loop, have the user enter a set of integers using prompt(). Add each entry to an array called myIntegers. Once the user is done entering integers have them enter ‘xxx.’
When the user has completed their data entry, provide the sum, average and product (result of multiplication) of the integers"
Here’s the code I have so far (not including the standard HTML div and script which is on another page):
let myIntegers = [];
let input = "";
let average = "";
let sum = "";
let product = "";
while(input !="xxx"){
input = prompt("Add numbers, end using xxx.");
if(input!="xxx"){
myIntegers.push(input);
}
}
console.log(myIntegers);
for(let x = 0; x < myIntegers.length; x++){
average = average + myIntegers[x]
}
document.getElementById("output").innerHTML =
average / myIntegers.length;
for(let y=0; y < myIntegers.length; y++){
sum = sum + myIntegers[y];
}
document.getElementById("output").innerHTML =
sum;
for(let z=0; z < myIntegers.length; z++){
product = product + myIntegers[z];
}
document.getElementById("output").innerHTML =
product * myIntegers;
This code presents "NaN" but the array in the console looks good. I’ve tried turning the prompt into numbers and I’ve changed up the order of the elements a dozen times. This code makes logical sense to me (except for the product, I’m not the best at math) but just doesn’t output what I want.
Any help is appreciated!
Thanks!
2
Answers
The text submitted by the user in the prompt is returned as a string or null. So, to perform any athematic operations on it, we need to parse it into the integer or float data type first.
Also, take care while initialization the variables, as if we define them with "", then the var will act as string type, and the + operation act as concatenation instead of addition.
Ex.Example of var intialized as "" act as string type
You can use the following possible code snippet to perform the same required task.