Reputation: 21
So I need some help trying to understand this code. I know the objective here for this function to loop through this array and find the maximum value. However I'm confused with what exactly "array[0]" and "array[i]" is. Thanks in advance.
var max_value = function(array) {
var result = array[0];
for (var i = 0; i < array.length; i++) {
if (array[i] > result) {
result = array[i];
};
}
return result;
}
console.log(max_value([1, 50, 2]));
Upvotes: 1
Views: 50
Reputation: 21
At the end of your code, you are calling the function (max_value) and passing in the array as a parameter to your function.
Your "result" variable is initially set to array[0], in your case, "result" is initially set to array[0] or "1".
var array = [1, 50, 2]
array[0] = 1
array[1] = 50
array[2] = 2
The number specified in the brackets after the array will locate the value at a certain position in the array.
The loop will iterate through your array by changing the i, or index/position, and comparing the value of the object in that array to your result variable. If the value at the next position of the array is larger than the current value of the result variable, the result variable will be reassigned to the result variable.
After the function has looped through the array, it will return result which will be the largest value found in the array.
Upvotes: 0
Reputation: 1303
An array is a sort of list of items. Imagine the below...
var array = ['one', 'two', 'three']; // [0]='one' [1]='two' [2]='three'
The value contained within array[0] is actually 'one', and so on (arrays start with an index of 0, not 1). When your loop runs, the i
gets incremented each time (that's the i++
part of your for loop) and so the arrays index (in this case [i]) being pointing at increases too, hence the value change each time through the loop.
function justDoesStuff()
{
// do some cool stuff then call returnSomeStuff()
var number = returnSomeStuff(); // number will equal 100
// notice no return statement
}
function returnSomeStuff()
{
return 100;
}
Upvotes: 2
Reputation: 1791
array[position] - means get the element from the 'array' which is at 'position'.
Now, if your array is
var array = ["a", "b", "c", "d"];
if you want to get the first and third element in the array.
array[0] -> a
array[2] -> c
Now, the same can be performed by providing the position as a variable.
var position = 0;
array[position] -> a
var position = 2;
array[position] -> c
This is generally used to traverse through an array in a loop or if the position is determined based on a condition during runtime.
Upvotes: 0