Uncaught TypeError: Cannot read properties of undefined (reading 'locations')

Viewed 160

I am trying to built a simple battleship game that I've found in a book, however I think some of the code in the book is outdated. I am trying to get the locations of ships in a table and give the user if the guess is a hit or a miss, however when I try to access locations of ships console throw this error. I would appreciate any help. This is the code:

let model = {
    boardSize: 7,
    numShips: 3,
    shipLength: 3,
    shipsSunk: 0,

    ships: [ { locations: ["06", "16", "26"], hits: ["", "", ""] },
             { locations: ["24", "34", "44"], hits: ["", "", ""] },
             { locations: ["10", "11", "12"], hits: ["", "", ""] } ],

    fire: function(guess) {
        for(let i; 0 < this.numShips; i++) {
            let ship = this.ships[i];
            let index = ship.locations.indexOf(guess);
            if(index >= 0) {
                ship.hits[index] = "hit";
                view.displayHit(guess);
                view.displayMessage("HIT!");
                if (this.isSunk(ship)) {
                    view.displayMessage("A battleship has sank!")
                    this.shipsSunk++;
                }
                return true;
            }
            view.displayMiss(guess);
            view.displayMessage("You missed.");
            return false;
        }
    },
1 Answers

You have a typo in the for loop condition:

for(let i; 0 < this.numShips; i++) {

should be:

for(let i = 0; i < this.numShips; i++) {
Related