I am trying to write a JavaScript program that will display the largest number out of 10 numbers inputted by the user. This is what I have so far but it isn't working.
var counter = 1;
var number = new Array();
number.length = 9;
var largest = 0;
while (counter <= 10) {
number = window.prompt("Enter Numbers 1-10 Number:" + counter + ".");
number[counter] = parseInt(number);
counter++;
}
largest = Math.max.apply(Array);
document.writeln("<h1>Largest number is " + largest + "</h1>");
You have several issues:
Arrays are 0
indexed. You skipped the 0
index by starting the counter at 0
, this will screw up the array calculation. If you go with Math.max.apply(array, number)
, it will work without the 0
indexing.
You overwrote the number
variable with every prompt, either use the window.prompt
to feed into the parseInt
or feed it into a temporary variable.
You had incorrect syntax for the apply variable.
var counter = 0;
var number = new Array();
number.length = 9;
var newnumber;
var largest = 0;
while (counter <= 10) {
newnumber = window.prompt("Enter Numbers 1-10 Number:" + counter + ".");
number[counter] = parseInt(newnumber);
counter++;
}
largest = Math.max.apply(Math, number);
document.writeln("<h1>Largest number is " + largest + "</h1>");
You're simply missing the expected thisArg
for Function.prototype.apply
.
The Syntax, as described by MDN is
fun.apply(thisArg[, argsArray])
As shown in this simple example
Math.max.apply (null,[5,4,3,7,9,]) //9
^^^^
where null
is used in the example for simplicity, as Math doesn't expect an specific context
What you are trying to do is passing the array number
to Math.max
, which would then be the thisArg
(though you seem to have it mistaken with Array
) which would result either way in Math.max
being called with zero arguments, which yields according to §15.8.2.11
Given zero or more arguments, calls ToNumber on each of the arguments and returns the largest of the resulting values.
- If no arguments are given, the result is −∞.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With