0
for(var i=0; i<5; i++) {
    inputArray[i] = prompt("Input book title, author, price with ,");
    function Book(title, author, price) {
        this.title = title;
        this.author = author;
        this.price = price;
    }
    var bookAfter = inputArray[i].split(",");
    var myBook = new Book(bookAfter[0], bookAfter[1], parseInt(bookAfter[2]));
    bookArray.push(myBook);
}

// Finding max price
for(var price in bookArray) {
    var first = bookArray[0];
    console.log(first);
    if(first[price] < bookArray[i+1][price]) {
        first = bookArray[i+1];
    }
}

Input information is like this

A, John, 10
B, Ashley, 15
C, James, 7
D, Emily, 9
E, George, 12

The problem is when I console.log(first.price), console.log(first[price]) or console.log(bookArray[3].price) I can get the right value of the price for example 10.

But the if statement gets error with this message Uncaught TypeError: Cannot read property 'price' of undefined when using if(first.price < bookArray[i+1].price) and gets another message Uncaught TypeError: Cannot read property '0' of undefined when using if(first.price < bookArray[i+1].price)

The basic for loop like for(var i=0; i<5; i++) doesn't work as well.

Any help would be appreciated :)

Park
  • 1
  • Consider what happens when `i` is 5 with an array of 5 items that's indexed starting at `0`. Since you're doing `i + 1`, you have that problem when you're doing the last item in the array. – T.J. Crowder May 24 '21 at 16:14
  • Side note: You're right to question whether to use `for-in` for this loop. Usually, no, it's not the right choice, see [this answer](https://stackoverflow.com/questions/9329446/for-each-over-an-array-in-javascript) (from me) for what to do instead. Typically these days it's `for-of`, or a basic `for` as you indicated in the question. If you want the index, just the basic `for` makes more sense. – T.J. Crowder May 24 '21 at 16:15
  • @T.J.Crowder Oh I missed that one. Right there's no bookArray[5] haha! Thanks I solved the problem :) – Park May 24 '21 at 16:24

0 Answers0