Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save prompt input into array

I`m having some issue with Javascript. We just started to study it a couple weeks ago and I have to do a work for class:

Need to do a prompt. get 10 numbers input (10 grades) from the user. put the numbers into an array and then do some functions with it.

My question is how do I save the input in the array? We learned about all the loops already. Tried to search online but didn`t found an answer.

I would love if somebody could explain how I do it. Thank you very much.

like image 912
Peter Toth Avatar asked Feb 05 '26 20:02

Peter Toth


2 Answers

Just try to ask them to input their numbers or grade, separated by a comma and then you can split on it.

var arr = prompt("Enter your numbers").split(",")

Or, ask prompt ten times

var arr = [];
for(var i = 0; i < 10; i++)
   arr.push(prompt("Enter a number");

If you want them to be numbers, just prefix prompt with +, so it becomes a number(provided they're actual numbers) or just do

arr = arr.map(Number);
like image 185
Amit Joki Avatar answered Feb 07 '26 11:02

Amit Joki


See the explanations in comments:

var arr = [];                               // define our array

for (var i = 0; i < 10; i++) {              // loop 10 times
  arr.push(prompt('Enter grade ' + (i+1))); // push the value into the array
}

alert('Full array: ' + arr.join(', '));     // alert the results
like image 31
Shomz Avatar answered Feb 07 '26 09:02

Shomz