I can't seem to figure out why the functions returns the "sum" after first for loop but not at the end of the function.
var a = [
[1, 1, 1, 0, 0, 0],
[0, 1, 0, 0, 0, 0],
[1, 1, 1, 0, 0, 0],
[0, 0, 2, 4, 4, 0],
[0, 0, 0, 2, 0, 0],
[0, 0, 1, 2, 4, 0]
];
function hourglassSum(arr) {
var sum = 0;
for (var i = 0; i < arr.length; i++) {
for (var j = 0; j < arr[i].length; j++) {
var sumTemp = arr[i][j] + arr[i][j + 1] + arr[i][j + 2] + arr[i + 1][j + 1] + arr[i + 2][j] + arr[i + 2][j + 1] + arr[i + 2][j + 2];
if (!isNaN(sumTemp) && sumTemp > sum) {
sum = sumTemp;
}
}
document.write('Sum: ' + sum + '<br/>');
}
document.write('Sum: ' + sum + '<br/>');
}
hourglassSum(a);
document.writestatements after the loop bodies end. See this example to learn how to return values from a function.jcan be the index of the last entry inarr[i], usingarr[i][j + anything_greter_than_zero]will result inundefined.