Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

html-javascript- object array

I was creating a web page that prints the name of the most expensive book after receiving five book information via the prompt () function. But when I print the name of an expensive book, only the title of the first book is printed. Can you see why?


<html>

  <head>
    <title>Create array of book objects</title>
    <script>
      function Book(title, author, price) {
        this.title = title;
        this.author = author;
        this.price = price;
      }

    </script>
  </head>

  <body>
    <h3>Create array of book objects</h3>
    <hr>
    <script>
      var i;
      var bookArray = new Array();
      var textSplit;

      for (i = 0; i < 5; i++) {
        var input = prompt("Enter book titles, authors, and prices, separated by commas.", "");
        textSplit = input.split(",");
        var book = new Object();
        book.title = textSplit[0];
        book.author = textSplit[1];
        book.price = parseInt(textSplit[2]);
        bookArray[i] = book;
      }

      for (i = 0; i < bookArray.length; i++) {
        document.write(bookArray[i].title + ", ");
        document.write(bookArray[i].author + ", ");
        document.write(bookArray[i].price + "<br>");
      }

      var most = bookArray[0];
      for (i = 0; i < bookArray.length; ++i) {
        if (bookArray[i].price > most) {
          most = bookArray[i].price;
        }

        // document.write(bookArray[i].title+"<br>");
      }
      document.write("<br> The most expensive book is " + most.title);

    </script>
  </body>

</html>
like image 959
morrie Avatar asked Dec 23 '22 21:12

morrie


1 Answers

The first book is only getting printed because you are comparing Object to Number. You should use .price property of the object to compare and assign the object to most

var most = bookArray[0];
for(i=0; i<bookArray.length; ++i){
   if(bookArray[i].price > most.price){
     most = bookArray[i];
   }
}
like image 156
Shikhar Tandon Avatar answered Jan 01 '23 12:01

Shikhar Tandon