Encountering NaN values in JavaScript arrays

I'm facing an issue with my HTML code that is supposed to make ball(s) bounce around the canvas. However, when I set the arrays storing the coordinates to random positions and test with

alert("Co-ordinates " + (cirX[i]) + " x " + (cirY[i]));
, it returns 'Co-ordinates NaN x NaN'. I tried doing it with a single ball without using arrays and it worked fine. I'm not sure if there's any mistake in how I'm coding my arrays or if it's something else. Here's my HTML:

<!Doctype HTML>
<head>
<script>
var cirX = [];
var cirY = [];
var chX = [];
var chY = [];
var width;
var height;

function initCircle(nBalls) {
  alert(nBalls)
  for(var i = 0; i<nBalls;i++) {
    alert("loop  " + i)
    chX[i] = (Math.floor(Math.random()*200)/10);
    chY[i] = (Math.floor(Math.random()*200)/10);
    cirX[i] = Math.floor(Math.random()*width);
    cirY[i] = Math.floor(Math.random()*height);
    alert("Co-ordinates " + (cirX[i]) + " x " + (cirY[i]));

    circle(cirX[i],cirY[i],3);
    setInterval('moveBall(i)',10);
  }
}

function moveBall(ballNum) {
    if(cirX[ballNum] > width||cirX[ballNum] < 0) {
      chX[ballNum] = 0-chX[ballNum];
    }
    if(cirY[ballNum] > height|| cirY[ballNum] < 0) {
      chY[ballNum] = 0-chY[ballNum];
    }
    cirX[ballNum] = cirX[ballNum] + chX[ballNum];
    cirY[ballNum] = cirY[ballNum] + chY[ballNum];
    circle(cirX[ballNum],cirY[ballNum],3);

}

function circle(x,y,r) {
  var c=document.getElementById("canvas");
  var ctx=c.getContext("2d");
  canvas.width = canvas.width;
  ctx.fillStyle="#FF0000";
  ctx.beginPath();
  ctx.arc(x, y, r, 0, Math.PI*2, true);
  ctx.fill();
  width = canvas.width;
  height = canvas.height;
}
</script>
</head>
<body>
<canvas id="canvas" width="400" height="300">
</canvas>
<script>
initCircle(3); //this sets the number of circles
</script>
</body>

I've researched how to initialize arrays correctly, but it still seems like I'm doing it right? Would appreciate any help on this matter!

EDIT:
Even after fixing the above mentioned issues, only one ball moves and at different speeds despite the variable ballNum in moveBall() ranging from 0 to 2 as expected (confirmed by adding alert(ballNum)). Any ideas why?

Answer №1

You refer to this code snippet

cirX[i] = Math.floor(Math.random()*width);

at a point when the variable width has not been defined yet. This will result in obtaining NaN as the output.

To correctly execute the moveBall function using setInterval, you can do so by utilizing

(function(i) { // encapsulating i to ensure its value is preserved (different from loop end
   setInterval(function(){moveBall(i)}, 10);
})(i);

Answer №2

One reason for this is that the width is not defined when the statement is first executed. To overcome this, you can fetch the canvas and its dimensions at the beginning and maintain them as global variables.

http://jsbin.com/agavoq/9/edit

When calling setInterval, you can use a self-invoking function to retain the value of i.

(function(x){
  setInterval(moveBall,10, x);
})(i);

Alternatively,

setInterval(moveBall,10, i);

Or,

setInterval('moveBall(' + i+ ')',10);

Answer №3

There seems to be another problem when examining this particular line

setInterval('moveBall(i)',10);

The value of i may not be as expected. It is recommended to avoid using a string within the setTimeout function.

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

Is there a way to change a model attribute in JSP based on the AJAX response?

I have a JSP page that contains the following code snippet: <li id="notifications"> <c:choose> <c:when test="${empty alerts}"> <p class="text-default">There are no Service Reminders at this time</p> ...

How can one effectively manage irregularly nested object/arrays within a Meteor framework?

Having difficulty finding a smart and effective method to manage nested arrays/objects with varying dimensions in nodeJS. These irregular arrays/objects can have 1, 2, 3, or more dimensions. For instance, consider these 2 different scenarios : Scenario 1 ...

What exactly does form.getHeaders(); mean?

Attempting to streamline the upload process, I have come up with the following code: var http = require('http'); var request = http.request({ method: 'post', host: 'https://www.ws-ti.4bank.com', path: '/img/create ...

Tips for maintaining state URL persistence after a page refresh in Next.js 13 when utilizing next-usequerystate

Currently, I am using the next-usequerystate library with Next Js 13. However, I have encountered an issue where the state on the URL is lost when I refresh the page. The initial URL looks like this: localhost:3000/?page=1&genres=tree But upon refres ...

Creating a dynamic tbody element on button click with the help of javascript or jquery

I am working with the following code: $(document).ready(function() { //Optimizing by selecting tbody first using jquery children var tbody = $('#myTable').children('tbody'); //If no tbody found, select the table itself ...

A loop variable in Javascript is a function that iterates

var x = 99; while (true) { function lyrics(person) { return x + " " + "lines of code in the file " + x + " " + person + (x-1) + " lines of code" + "!"; } console.log(lyrics("John strikes one out, clears it all out ;")); x -= 1; if (x ...

Encountered an issue while attempting to start the JavaScript debug adapter in Visual Studio

When attempting to debug my script code in Visual Studio, I encountered an error. How can I resolve this issue? ...

Exploring the capabilities of Realm while interacting with and processing JSON data

Recently, I started working with Realm in my project and encountered an issue while trying to parse JSON and save it using Realm. The error arises when attempting to loop through the result array. 'Attempting to modify object outside of a write tra ...

The image is not displaying on the page

Slider Section (Gray Part) We verified after loading, and the data was spot on. In development mode (F12), we can inspect object information (ImgURL, Text, etc.). However, it is not being displayed. Below is the template code and script code. Thank you. ...

What is the best way to verify a date in the format (yyyy-mm-dd) using jQuery?

I'm in the process of validating a date with the format (yyyy-mm-dd). I came across a solution, but it's not quite what I need as it's in the format (mm/dd/yyyy). You can check out the solution here: http://jsfiddle.net/ravi1989/EywSP/848/ ...

JavaScript - utilize regular expressions to check if the argument starts with a forward slash

Currently, I am utilizing nodejs for API testing purposes. To properly test the logic within this if statement, I am in search of a string that aligns with this specific regular expression. if (arg.match(/^\/.*/)) { // ... } Would anyone be able ...

AngularJS- numerous unique directives featured on a single page each with its distinctive state

Regarding the query about Calling a method in a directive controller from another controller. Is there a way to have multiple separate directives of the same type on a page? Since they share a common API (singleton), the state is also shared. Therefore, i ...

How to retrieve values from HTML class names using Javascript for loops but encountering issues

foreach($products as $row){ <input type="hidden" class="prodId" name="id" value="<?php echo $row['id']; ?>"> <input type="hidden" class="prodUnique" name="unique" value="<?php echo $unique; ?>"> <button id="added" ...

Deleting identical string objects from two arrays or lists in Java

My first question here is regarding Java programming. I want to implement a specific logic: I have two string Arrays (or Lists of strings). One array named asu includes elements M1, M2, M3 ... The other array called rzs consists of elements M1, M2, M3 ...

What could be causing the error when trying to use a PUT request with fetch in Vue?

Whenever I attempt to send a PUT request, an error pops up on the console. export function putUserData() { fetch(`${url}/user/${getCookie("ID")}`, { method: "PUT", headers: { "Authorization": `B ...

Error: Module not located in Custom NPM UI Library catalog

I have recently developed an NPM package to store all of my UI components that I have created over the past few years. After uploading the package onto NPM, I encountered an issue when trying to use a button in another project. The error message "Module no ...

Cheerio in node.js encounters a problem while reading HTML files

I am brand new to JavaScript and I've hit a roadblock with Node Cheerio. Any assistance would be greatly appreciated. The code I'm currently working on can be found here: https://github.com/zafartahirov/bitstarter. Once the issue is resolved, t ...

navigation through sibling views using query-based route in ui-router

Imagine an app with two sides: "left" and "right", each with tabs. The application's URL structure is formatted like this: app/splitscreen/?leftTab=1&rightTab=1 Currently, the HTML template is set up as follows: <!-- splitscreen.tpl.html --& ...

Vuetify: How to restore the input value in v-text-field

This app is designed with a simple v-text-field for user input. The issue I am facing is that when I enter a combination of numbers and letters like 11a, then quickly tab out or click out of the input field before losing focus, it only shows 11. However, ...

The filter functionality isn't functioning properly when attempting to filter an array of objects within a Vuex action

I have a collection of objects that is accessed through a getter. I am using this getter inside an action to filter the items, but no matter what I do, the filtering does not seem to work and it ends up returning all the mapped item IDs. filterItems({ gett ...