Error: Attempting to assign a value to property 'x' of an undefined object has resulted in a TypeError

When I tried to create an array of randomly generated circles (stars) in my first code, I encountered a TypeError on this line:

stars[i].x = Math.floor(Math.random() * w)

Even though stars is defined in the code, the issue persisted.

$(document).ready(function() {
//Canvas
var canvas = $("#canvas")[0];
var ctx = canvas.getContext("2d");
var w = $("#canvas").width();
var h = $("#canvas").height();
var stars = [];

The remaining code seemed correct, but including it here might highlight any other mistakes that slipped past me.

$(document).ready(function() {
//Canvas
var canvas = $("#canvas")[0];
var ctx = canvas.getContext("2d");
var w = $("#canvas").width();
var h = $("#canvas").height();
var stars = [];


function init() {
    createStars();
    drawStars();
}

init();

function createStars() {
    for (var i=0; i<=4; i++) {
        stars[i].x = Math.floor(Math.random() * w);
        stars[i].y = Math.floor(Math.random() * h);
    }
}

function drawStars() {
    for (var i=0; i <= 4; i++) {
        ctx.beginPath();
        ctx.arc(stars[i].x, stars[i].y, 10, 0, 2 * Math.PI);
        ctx.stroke();
    }
}
});

This being my initial attempt at programming, troubleshooting is not yet my strong suit. Thank you for any assistance provided.

Answer №1

init array is established, but are the stars[i] objects present? It is necessary to explicitly generate those objects:

function generateStars() {
    for (var i=0; i<=4; i++) {
        stars[i] = {};
        stars[i].x = Math.floor(Math.random() * w);
        stars[i].y = Math.floor(Math.random() * h);
    }
}

or use a more concise syntax:

function generateStars() {
    for (var i=0; i<=4; i++) {
        stars[i] = {
            x: Math.floor(Math.random() * w),
            y: Math.floor(Math.random() * h)
        };
    }
}

Answer №2

stars has been declared, but you are not accessing stars[0] in your for-loop.

To correct this issue, your loop should look like the following:

for (var i=0; i<=4; i++) {
    stars.push({
      x: Math.floor(Math.random() * w),
      y: Math.floor(Math.random() * h)
    });
}

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

Unable to hear sound - JavaScript glitch

Spent countless hours trying to figure this out - Can't get the audio file to play when clicking an HTML element. var sound = document.querySelector(".soundfile"); function playAudio() { sound.play(); } document.querySelector(".btn-hold").addE ...

decipher the string using various operators

Is it possible to explode a string using different operators? I am trying to extract every code (of varying sizes) between the brackets [ and ] Here are some examples of the different possibilities: const codes = [ '[5018902847][592][50189272809] ...

Having trouble with NextJS when trying to add an item to an element and render it in a Tailwind select

Struggling with displaying dynamic values in a select box using NextJS After fetching data from an API endpoint, I aim to populate a select box. However, my goal is to prepend a new element to the 'teams' array and ensure it appears first upon p ...

Activate the class when clicked

I am facing a minor issue with the JavaScript onClick function. I need a function that will target a specific class, like .modal. Currently, it looks like this <div class="modal" onclick="modalFix()"> <p>here is some text</p> </div> ...

The absence of 'www' in the ajax path is causing an error

Apologies for my poor English as I am currently a student. My issue is related to the use of ajax without "www" in the URL. Let me demonstrate. var path = "www.sinemayolu.com"; //Real-time Ajax Search $('.searchtext').keyup(function ...

Is there a way to eliminate get variables and filename from a URL using JavaScript or jQuery?

I've been researching this issue, but unfortunately, I haven't been able to find a definitive solution for my specific needs. Let's say I have a URL like... How can I extract this URL and remove the "index.php?search=my+search" part so that ...

Execute jQuery after Angular has completed its loading process

I'm currently working on making some small adjustments to an existing website. This website was originally created using Angular. While my code is written with jQuery, I do have the flexibility to use any type of JavaScript necessary. Despite this, ...

Typescript enhances React Native's Pressable component with a pressed property

I'm currently diving into the world of typescript with React, and I've encountered an issue where I can't utilize the pressed prop from Pressable in a React Native app while using typescript. To work around this, I am leveraging styled comp ...

Setting the maximum length value in HTML dynamically

There is an input field with specific formatting restrictions, such as a maximum length of 6 characters and only accepting numeric values. On blur event, the 6-digit code "123456" is automatically formatted to "12-34-56" and the browser remembers this form ...

Having Trouble Sending Text to InputBox Using Selenium WebDriver

Greetings everyone Can someone guide me on how to use Selenium to input a Login and Password in an Alert Dialog Box? Upon loading the webpage, the alert is already displayed: https://i.stack.imgur.com/F1O5S.png I have attempted the following code: Str ...

Issue with Vue method not providing expected output

As I dive into the world of Vue, I find myself facing a peculiar issue with a method that should return a string to be displayed within a <span>. While I can successfully retrieve the correct value through console.log, it seems to evade passing into ...

Encountered a React error stating: `TypeError: this.state.projects.map is not a

export default class Timeline extends Component{ state = { projects : [], }; async componentDidMount(){ const response = await api.get("/projects"); this.setState({projects: response.data}); } render(){ return ( <div className ...

Retrieve the specific day of the previous complete week within a designated month using JavaScript

Is there a way to determine the last full week of any given month? For example, I need to find the Wednesday of the last full week in April each year. Here is the desired output: April 24, 2019, April 22, 2020, April 28, 2021, April 27, 2022, and so on. v ...

`Is there a way to choose several radio buttons with varying names using just one label?`

Is there a way to choose multiple radio buttons with different names using just one label? Here's an example of what I'm attempting to accomplish... <input id="1A" type="radio" name="first" value="A">firstA<br> <input id="1B" typ ...

What is the method for initiating a POST request in Java Script without including any data?

Currently, I am utilizing Ajax to send an array to the router, as demonstrated below... var send = function () { var data = search console.log(data) $.ajax({ type: 'post', url: ...

What is the best way to save the raw text or event-stream data from a JavaScript get request when the server is continuously loading?

Currently, I'm attempting to fetch some basic data from an API. Here is the URL for the request: The issue lies in the fact that the server appears to keep refreshing the page constantly. This endless loading occurs both when using a browser and with ...

The code is slicing data, but the changes are not reflecting in the user interface

Initially, there are three drop down menus displayed. Upon selecting an option from the first drop down menu, the values in the second drop down menu load. After selecting an option from the second drop down menu, a new set of drop downs appears. However, ...

What is the best way to arrange the keys within a nested object in JavaScript?

Question: { "foo": "bar", "bar": "baz", "baz" : { "nestedKey": "foo" } } In order to sign this request using the Hmac512 algorithm, I must first stringify the object. I am concerned that if the key order is not preserved, the generated signature on the ...

Visualizing Data with d3.js Force Chart: Integrating Images with Nodes for Dynamic Animation

After enhancing a force diagram to compare two profiles, I am faced with the challenge of getting the main node to display an image. View comparison here How can I centrally align and size the image correctly while making the thumbnail data from the JSO ...

How to Implement a Loop Inside a JavaScript Alert or Prompt?

Seeking clarity: Is it possible to embed code into an alert() or prompt()? For example, is there a way to include a loop or add data to the alert() or prompt just before execution or during execution? -Appreciate any help ...