Tell us what’s happening:
Hi everyone. English is not my native language , I’m sorry if there are some errors in spelling or grammar.
I got two problem with this lecture.
The first:
I know the code works but I don’t understand why the result is 5040.
Can someone show me the math behind it?
The other problem is the following:
I know " for (var i = 0; i < arr.length; i++) " checks the number of arrays.
I know " for (var j = 0; j < arr[i].length; j++ " checks the numbers in the arrays.
But it only checks the length of the numbers.
The actual array is passed into the function as argument as I understand it.
How does the function calculate with the arguments when I only check the length of an array?
I’m sorry this all might sound weird but I can’t explain it any better.
Maybe some one can explain this whole function to me at a very basic level?
Your code so far
function multiplyAll(arr) {
var product = 1;
// Only change code below this line
for (var i = 0; i < arr.length; i++){
for (var j = 0; j < arr[i].length; j++ )
product = product * arr[i][j];
}
// Only change code above this line
return product;
}
multiplyAll([[1,2],[3,4],[5,6,7]]);
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.183 Safari/537.36.
This function takes in an array of arrays and finds the product of all numbers in these arrays.
Your outer loop basically says ‘go through all of the arrays in our big array’.
The inner loop says ‘go through all of the numbers in each sub array’.
With each number in each sub array, we multiply that number by the current value of the product.
The length there means ‘how many subarrays’ and ‘how many numbers’. We aren’t taking the length of any numbers themselves. That would generate an error.
Nested loops can be really confusing at first. So it just takes times to get used to how they work. But you will have plenty of chances to work with them throughout the FCC curriculum.
I think the key thing to remember is that product doesn’t’ just stay at 1. It is constantly being updated.
How the math works
when i=0
product = 1 * 1(arr[0][0]), the result for product is still 1
product = 1 * 2(arr[0][1]), the result for product is now updated to 2
when i=1
product = 2 * 3(arr[1][0]), product is now updated to 6
product = 6 * 4(arr[1][1]), the result for product is now updated to 24
when i=2
product = 24 * 5(arr[2][0]), product is now updated to 120
product = 120 * 6(arr[2][1]), the result for product is now updated to 720
product = 720 * 7(arr[2][2]), the result for product is now updated to 5040