Kippy
Kippy

Reputation: 13

JavaScript - Everything being stored from for loop stores as undefined

I have recently gotten started in using the JavaScript programming language. No, this is not my first language, but this is one of my first time using it. I am trying to create a chess program using the HTML5 canvas capability. I am using a for loop to create an array of all of the positions for the chess pieces. I run into one problem; it stores all of the coordinates as undefined. Bellow is the code for the functions that store these values.

var board = [];

function createBoard() {
  var integer = 0;
  for (var i = 0; i < 8; i++) {
    for (var j = 0; j < 8; j++) {
      board[integer] = new Position(i, j);
      integer++;
    }
  }
}

function replacePosition(position1, position2) {
  var i = board.indexOf(position1);
  board[i] = position2;
}

function getPosition(x, y) {
    for (var position in board) {
      console.log("(" + position.x + "," + position.y + ")");
      if (position.x == x && position.y == y) {
        return position;
      }
    }
    return null;

Here is the Position class if you need it.

class Position {
  constructor(x, y) {
    this.x = x;
    this.y = y;
    this.piece = null;
  }
}

I run createBoard(), and then I attempt to use getPosition(). I says that my code does not work with a null value. If I look at the console, it keeps logging "(undefined,undefined)." I did a little research, but the only thing I could find was asynchronous. I tried to look into that, but I could not figure out how to fix it. Does anyone know how to fix this?

Upvotes: 1

Views: 43

Answers (2)

Pointy
Pointy

Reputation: 413712

A for ... in loop in JavaScript iterates over the property names of an object, not the property values.

You shouldn't use a for ... in loop anyway. Use a for loop with a numeric index variable, or else use .forEach() or one of the other Array iterator methods (in this case probably .find()):

function getPosition(x, y) {
  for (var i = 0; i < board.length; ++i) {
    var position = board[i];
    console.log("(" + position.x + "," + position.y + ")");
    if (position.x == x && position.y == y) {
      return position;
    }
  }
  return null;
}

or

function getPosition(x, y) {
  return board.find(function(p) {
    if (p && p.x == x && p.y == y)
      return p;
    return false;
  };
}

Upvotes: 1

rasmeister
rasmeister

Reputation: 1996

I would just do

function getPosition(x, y) {
  return board[x*8 + y];
}

Upvotes: 2

Related Questions