What am I doing wrong? I’m trying to display the predefined array. Then a function to display the highest number in the array and it’s index. The last thing is create a function that displays each number in the array if it’s odd or even. Thank You in advance.
var arr = [56, 77, 23, 12, 88, 59, 97, 33, 38, 64];
var string = newarr[10];
string[0] = "56";
string[1] = "77";
string[2] = "23";
string[3] = "12";
string[4] = "88";
string[5] = "59";
string[6] = "97";
string[7] = "33";
string[8] = "38";
string[9] = "64";
var max;
var maxIndex;
var newarr;
function findMax(arr) {
var max = arr[0];
for (var i = 0; i < arr.length; i++) {
if (max < arr[i] ) {
max = arr[i];
maxIndex = i;
}
}
}
function evenOrOdd(string) {
if (string % 2 == 0) {
console.log(string + "is even");
} else {
console.log(string + "is odd");
}
}
console.log (arr);
console.log("The largest number in the array is " + max + " located at array index " + maxIndex);
console.log("The numbers were:");
You have never given a value to newString, its value is undefined, and undefined is not something you can use bracket notation on. You need to define your values before using them
var arr = [56, 77, 23, 12, 88, 59, 97, 33, 38, 64];
var max, maxIndex;
function findMax() {
var max = arr[0];
for (var i = 0; i < arr.length; i++) {
if (max < arr[i] ) {
max = arr[i];
maxIndex = i;
}
}
}
console.log (arr);
console.log("The largest number in the array is " + max + " located at array index " + maxIndex);
I should have looked a little more carefully at your code. Yes, there is a potential scope issue, but also, you aren’t calling findMax, and the function doesn’t return a value, which is sort of OK if you are going to work on the global variables, but I recommend you pass arr into the function and then return the values you want.