Having trouble understanding what’s going on in this function per line. See comments below - please correct my logic and/or explain what’s going on.
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 *= arr[i][j];
/* var i = 0; i < arr.length; i++
i = [1]; 1 < 3; i++
i = [2]; 2 < 3; i++
i = [3]; 3 < 3; end
1 * 3 = 3
j = [1]; 1 < 1; j++
j = [2]; 2 < 1; end
1 * 2 = 2
3 * 2 = 6
Is that correct? */
}
}
// Only change code above this line
return product;
}
// Modify values below to test your code
multiplyAll([[1],[2],[3]]);
product *= arr[i][j]
Since product = 1, isn’t this technically 1 * i * j?
When i = 0 and j = 0, then it goes to the first array in multiplyAll which is 1. So it’s then product * i * j = 1 * 1 * 1? Likewise, if it were multiplyAll([1, 2], [2], [5, 10]]), then it would be: i = 0 => arr[1, 2] and j = 0 => 1, since 1 takes position 0 in array [1, 2]?
So then, product *= arr[i][i] => 1 * 1 * 2 * 1 = 2? Where the first 1 comes from product = 1, 1 * 2 comes from multiplying the array values of [1, 2], and the last 1 comes from j = 0 => 1 in [1, 2].
i = 0; j = 0; arr[0][0] = 1
product = 1 * 1 = 1
i = 1; j = 0; arr[1][0] = 2
product = 1 * 2 = 2
i = 2; j = 0; arr[2][0] = 3
product = 2 * 3 = 6
Why does j = 0 for all instances; does it never iterate past 0?
Ah, I understand! However:
multiplyAll([[1],[2],[3]]);
i = 2; j = 0; arr[2][0] = 3
product = 2 * 3 = 6
How does this = 6? If i = 2, then it’s referring to 3, but if j = 0, then it’s referring to 1. In that case, shouldn’t it be 1 * 3 * 1 (product * i * j)?
In this exercise though, product = 1. So if i = 2 and j = 0, then it’s:
1 * 3 * 1 = 3 (given that multiplyAll([[1],[2],[3]]))
This is how I understand the exercise and I’m not sure what I’m not getting