You're almost there, but you're only prompting once and placing the input in to a variable. You need to prompt 10 times if you want 10 numbers (otherwise you need to parse the input and extract 10 numbers from it).
Assuming you wanted a few methods of populating elmt
through ask
(here i use input
instead of ask
and nums
instead of elmt
--but we're talking minor semantics):
Method one, prompt 10 times:
// initialize array with 10 elements
var nums = new Array(10);
// iterate over each element and prompt for value
for (var i = 0; i < nums.length; i++){
var input = prompt('Enter number ' + (i + 1) + ' of ' + (nums.length + 1));
// place value (as a number) into the array
nums[i] = new Number(input);
}
/* sum/average code */
Method two, prompt once and String.prototype.split
:
// initialize array with 10 elements
var nums = new Array(10);
// prompt for 10 numbers
var input = prompt('Enter ' + (nums.length + 1) + ' numbers separated by commas:');
var values = input.split(',');
// check we have the right amount
if (values.length == nums.length){
// iterate over the values
for (var i = 0; i < nums.length; i++){
// place the input (as a number) into the array
nums[i] = new Number(values[i]);
}
}
/* sum/average code */
Method three, input boxes:
<script>
function average(){
// initialize array with 10 elements
var nums = new Array(10);
// iterate over the elements
for (var i = 0; i < nums.length; i++){
// grab <input> based on id attribute
var input = document.getElementById('num' + i);
// insert the value (cast as a number) in to the array
nums[i] = new Number(input.value); // case to number
}
/* sum/average code */
}
</script>
<p>Enter 10 numbers:</p>
<input type="text" id="num0" />
<input type="text" id="num1" />
<input type="text" id="num2" />
<input type="text" id="num3" />
<input type="text" id="num4" />
<input type="text" id="num5" />
<input type="text" id="num6" />
<input type="text" id="num7" />
<input type="text" id="num8" />
<input type="text" id="num9" />
<button onclick="average()">Click to average</button>