JavaScript - All values stored from the for loop are registering as undefined

Recently delving into the realm of JavaScript programming, I find myself faced with a new challenge. While not my first language, this is one of my initial ventures with it. My current project involves creating a chess program utilizing the HTML5 canvas feature. To achieve this, I am using a for loop to generate an array containing all the positions for the chess pieces. However, I have encountered an issue where these coordinates are being stored as undefined. Below are the functions responsible for storing 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;

Below you will find the Position class required for reference.

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

Upon executing createBoard(), attempting to utilize getPosition() throws errors related to handling null values. Reviewing the console output reveals a continual stream of "(undefined,undefined)." Despite research efforts pointing towards asynchronous issues, resolving them has proven elusive. Could someone provide guidance on remedying this situation?

Answer №1

I personally prefer to use

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

Answer №2

When using a for ... in loop in JavaScript, it iterates over the property names of an object rather than the actual property values.

It's advised not to utilize a for ... in loop for this purpose. Instead, opt for a for loop with a numeric index variable or leverage methods like .forEach() or perhaps .find() when dealing with arrays:

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;
}

Alternatively,

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When scrolling down, the popup window shifts its position

I have implemented a popup window which displays a list on hover. It works perfectly on the default page, but when I scroll down, the popup also moves with the scrollbar. Below is the HTML code that creates the hidden popup list initially and shows it on ...

Chart showing a Google Timeline: Allow for each bar to be colored differently when there are multiple bars on the same line

It appears that the Google Timeline charts have a feature to color individual blocks on the timeline as indicated in the documentation at However, there seems to be an issue when two bars overlap on the same line, which is evident in this fiddle: http://j ...

Passing PHP values to JavaScript and then to AJAX requires using the appropriate syntax and techniques for

Currently, I am populating a table with data retrieved from my database. Here is a snippet of the code: <?php //mysqli_num_rows function while($row=mysqli_fetch_array //I know this may be wrong, but that's not the point echo "<tr><t ...

How can I toggle button states within a v-for loop based on input changes in Vue.js?

Within the starting point of my code: https://plnkr.co/LdbVJCuy3oojfyOa2MS7 I am aiming to allow the 'Press' button to be active on each row when there is a change in the input field. To achieve this, I made an addition to the code with: :dis ...

Discover the ID or HREF linked to the current date using moment.js

I'm looking to dynamically add an active class to the current day in my web application. An example of how it currently works is shown below: $( document ).ready(function() { $('a[href*="2208"]').addClass('active'); }); My goal ...

Struggling to construct a project using parcel, continually encountering issues with unsupported file types

My attempt at creating a project using parcel has hit a snag. Despite diligently following the guidelines provided in my assignment, an error message consistently appears in my terminal each time I initiate the command: parcel src/index.html The error mes ...

Showing dynamic icons in Angular 2 applications

My goal is to dynamically load a part of my website, specifically by using icon classes defined in the interface like this: import { OpaqueToken } from "@angular/core"; import {IAppConfig} from './app.interface' export let APP_CONFIG = new Opaq ...

Combining the power of Vuforia with the capabilities of Three

I'm having difficulty with the integration of three.js and Vuforia, as I have limited knowledge about OpenGl which makes it challenging to troubleshoot. Our team is working on a small AR app where we aim to utilize Vuforia for tracking and recognitio ...

Ajax is updating the initial row of an HTML table while the subsequent rows remain unchanged and retain their default values upon modification

I need help with updating the status of a user, similar to what is discussed in this post. The issue I am facing is that only the first row of the table updates correctly. Regardless of the selected value from the dropdown list on other rows, the displaye ...

Using Try and Catch effectively - tips and strategies

As I delve into learning JavaScript on my own, one topic that caught my attention is the try/catch structure. The tutorial I came across only covers how to implement it, but lacks in explaining its practical applications. Is there anyone who can shed som ...

Node - ensure that each API call finishes before initiating the next one

Currently, I am encountering an issue with my POST request within the 'add-users' route. I have initialized an array named success and aim to trigger the next API call once a response is received. It seems that the problem lies in sending too ma ...

What is the best way to transfer the main-video-wrap div into the video-list-Wrapping div?

Thank you @Kathara for your valuable assistance I have successfully set up the video layout with a picture-in-picture mode option. When I click on a video to move it to the background, it works well. However, I am facing difficulty in moving the entire vi ...

Generating pop-up upon loading with CSS3

I have searched through numerous threads and forums in the hopes of finding a solution, but I haven't been successful. My issue lies with triggering a popup on my website. I followed online tutorials to create a popup window, which I was able to do su ...

Is it possible to have more than one button for each item on my Shopping List App?

I am developing a shopping list app that allows users to add items to a list. Each item added triggers the display of a button next to it, enabling users to remove the item from the list when needed. However, a problem arises as more items are added – i ...

Error occurs when running Visual Studio Code locally - variable not defined

After successfully going through a Microsoft online demo on setting up an httpTrigger in Visual Studio Code with JavaScript to upload it to Azure Functions, I decided to customize the code for a specific calculation. I managed to get the calculation done a ...

What could be causing my React component to only render after pressing ctrl + shift + R?

I am facing an issue with my chrome extension where it only appears after refreshing the page using ctrl + shift + r. However, there is a new problem that arises when I click on a link that refreshes the page, causing the extension to disappear and requiri ...

Is it possible for the Redux inside a React component from npm to clash with the Redux in the container?

I am looking to bundle a React component with npm and incorporate Redux to handle state within the component. If another React project imports my component, will it cause conflicts with the Redux instance of that project? For example: The component code ...

Error: The DOM is throwing an uncaught TypeError because it cannot read the property 'children' of an undefined value

After delving into the depths of the DOM, I zeroed in on a specific element that I was eager to access. To reach this elusive element, I meticulously navigated through the DOM using the following code snippet: var body = document.body; var bodych ...

React's useState Hook: Modifying Values

I just started learning about React and React hooks, and I'm trying to figure out how to reset the value in useState back to default when new filters are selected. const [apartments, setApartments] = React.useState([]) const [page, setPage] = React.us ...

The TS2769 error occurs when trying to change the react calendar due to no matching overload in the

The calendar functionality in my project was implemented using the response calendar library. Suddenly, I encountered an onChange prop error in the default code. This was working fine before. What steps should I take to resolve this issue? Here is my cod ...