Reputation: 599
I know a solution to this using Math.max(), but rather I was hoping someone could explain why the following doesn't work.
array = [4, 5, 1, 3]
for (var i = 0; i < array.length; i++) {
var num = 0;
if (array[i]> num) {
num = array[i];
}
}
The above just gives the last number in the array as num
. So my guess is that array[i]
isn't appearing as a number (but perhaps as a string) in the conditional. Please forgive my incomplete understanding of JS. Any help is much appreciated!
Upvotes: 3
Views: 87
Reputation: 386578
Just some hints:
var array = [4, 5, 1, 3],
i,
max = array[0];
for (i = 1; i < array.length; i++) {
if (max < array[i]) {
max = array[i];
}
}
console.log(max);
Upvotes: 1
Reputation: 28850
The real answer to your question is to learn how to debug JavaScript code. Your web browser has a debugger built in that will let you step through your code statement by statement and view all your variables each step of the way. Please try this; it will help you immensely.
Simply add a debugger;
statement before the first line of code, then open the developer tools and reload your page. The debugger will stop on that statement, and then use the Step In button in the debugger to single step through the code.
To make it easy for you to get started, here is a copy of your original code (with the bug) as a snippet with the debugger;
statement added:
function test() {
debugger;
array = [4, 5, 1, 3]
for (var i = 0; i < array.length; i++) {
var num = 0;
if (array[i]> num) {
num = array[i];
}
}
}
test();
It's best to put the code you're testing inside a function as I did here. That lets you look at your local variables without the standard global variables and functions cluttering the view.
Open the developer tools and then run the snippet, then use the single step button as I mentioned above.
Every browser has developer tools built in that work in a similar way. For example, here is a guide to the Chrome DevTools.
Upvotes: 4
Reputation: 5613
You keep resetting num
to 0
in your loop. You need to move the variable declaration and assignment outside:
array = [4, 5, 1, 3]
var num = 0;
for (var i = 0; i < array.length; i++) {
if (array[i]> num) {
num = array[i];
}
}
console.log(num);
Upvotes: 4