Unable to locate the JavaScript function

My latest 'object' creation:

function Gem()
{
    this.size = 20.0;
    this.body;
    this.isCollected = false;

    this.vertexPosBuffer;
    this.vertexColBuffer;
}

Next, I define a function for it:

Gem.prototype.Update = function()
{
    this.body.ApplyForce(new b2Vec2(0, 5), this.body.GetPosition());
}

Finally, I populate an array with gems:

var gems;
function AddNewGem()
{
    var newGem = new Gem;
    var position = new b2Vec2;
        position.x = Math.random()*(canvas.width+1);
        position.y = Math.random()*(canvas.height+1);
    newGem.InitializeRandom(position);
    gems.push(newGem);
}

To update all gems, I use the following function:

function UpdateGems()
{
    for(var gem in gems)
    {
        gem.Update();
    }
}

However, I encountered the following error:

Uncaught TypeError: Object 0 has no method 'Update'

Oddly enough, the "InitializeRandom(...)" methods, added in the same manner, do work...

What am I missing here?

Answer №1

The issue you're facing is that the for in loop is not designed for iterating through arrays. It's specifically used for enumerating object properties.

Instead, you should opt for a standard for loop like this:

for(var i = 0; i < rocks.length; i++) {
    rocks[i].Tick();
}

Answer №2

To properly set up your program, it is essential to initialize your variables:

function Rock() {
    this.size = 30.0;
    this.body = {};     //Begin with an object
    ...
}
var rocks = [];   //Start with an empty array
function GenerateNewRock() {
    ...

Furthermore, as rocks is an array, it is recommended to use a for loop for iteration:

function UpdateRocks()
{
    for(var i=0, l=rocks.length; i<l; i++)
    {
        var rock = rocks[i];
        rock.Update();
    }
}

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

Jenkins server is encountering failing Protractor test cases, while they successfully pass on a local machine. The error message displayed is "Element is not clickable

In my script, I have developed a functionality to create and delete a form, triggering a modal dialogue box with "Create" & "Delete" buttons. The script works fine on my local machine but fails on the Jenkins server with the following error message: [31mU ...

Generating dynamic strings for identifiers in JSX

Can you help me figure out how to dynamically create IDs like this? <div id="track_1"></div> <div id="track_2"></div> I tried assigning the IDs from the parent component like this: export default function Compon ...

Activate an action only upon closing the page

I am looking for a solution in my vue.js app to execute a function only when the user closes the application. I have tried registering an event listener for beforeunload, but it causes the function to also trigger on page reloads, which is not ideal. Is t ...

Looping through arrays with for loops

I have an array named blockHeights which consists of 3 values: 1, 2, and 3. This means that blockHeights[0] is equivalent to 1. Additionally, there is a loop present: for (int i = 1; i <= blockHeights.length; i++) At the start of the loop, I wish to ...

What is the best way to eliminate all frames from the current windows using jQuery?

When transitioning to another page from my center frame, I need to ensure that the top and bottom frames are not visible in the new page. This will prevent my spinner or footer from showing up on the page I'm navigating to. Is it possible to achieve ...

Exploring the basics of Three.js: a step-by-step guide using a shadertoy example on transforming patterns with objects

Check out this snippet, inspired by the second live example found at : html, body { height: 100%; margin: 0; } #c { width: 100%; height: 100%; display: block; } <canvas id="c"></canvas> <script type="module"> // Three.j ...

Numpy now has the ability to automatically convert np.arrays into lists with implicit conversion

In the process of creating a `numpy.array` of other `numpy.array's` for a Monte Carlo simulation, I am encountering an issue. I am attempting to take an element of the array (which is another 1d array), perform a function on it to return a subsection ...

Explore flat data querying using Firebase and AngularFire

I am working with data stored in firebase, utilizing a flat structure with key-value pairs to establish a many-to-many relationship between events and users (see figure 1). While it's straightforward to look up events associated with a user using pure ...

Is It Possible to Save Data to Local Storage Using Vue.js?

I am currently working on storing data using Vue.js and local storage. By writing localStorage.set('something', 5) in my main.js file, I can view the data in the Chrome dev tools under the 'Storage' section in the 'Application&apo ...

Strategies for transmitting computed variables from a controller to JavaScript once the computation is complete?

Within my application, I have a button that triggers an action called "method" present in the UserController. This particular action involves executing some specific tasks. def method ***performing necessary calculations and operations*** @my_variable ...

What is the best way to enhance the class following this condition in JavaScript?

Initially, the original script worked perfectly with just one class being added: function check_btn_charge() { if (parseInt(jQuery(".total-change-price").text()) >= 0) { jQuery(".btn-action-save-charge"+"&nbsp;"+"btn-danger" ...

JQGrid is a unique event grid that triggers only once for the inaugural loading, allowing users to apply a default filter upon first loading

I am currently using JQGrid (jQuery jQgrid not Gurrido) version 4.6.0 and I am in need of an event that occurs only once the grid has completed loading for the first time. I have attempted to use loadComplete and gridComplete, but it seems they both perfor ...

VUE JS - My methods are triggering without any explicit invocation from my side

I've encountered a frustrating problem with Vue JS >.<. My methods are being triggered unexpectedly. I have a button that is supposed to execute a specific method, but this method gets executed along with other methods, causing annoyance... Her ...

Extracting array elements from JSON using PHP

In this project, I am analyzing the JSON data available at this link: My main goal is to extract the information from the tags[{"name":""}] section. Specifically, I am interested in retrieving the 'container' value from '"name":"Container"& ...

A guide on combining multiple arrays within the filter function of arrays in Typescript

Currently, I am incorporating Typescript into an Angular/Ionic project where I have a list of users with corresponding skill sets. My goal is to filter these users based on their online status and skill proficiency. [ { "id": 1, ...

Utilizing JQUERY and AJAX for conditional statements

I am currently in the process of creating a basic chat bot. At this point, the bot replies when the user inputs a pre-defined question. However, I am trying to figure out how to program the chatbot to respond with a "sorry, I don't understand" message ...

How can I make sure addEventListener only responds to numbers and not images?

Currently, I am facing a dilemma with implementing a button that features an image on it and needs to be placed within another div. Despite successfully achieving this, I am struggling to comprehend the JavaScript code outlined in a tutorial I followed. Th ...

Node is not functioning properly with Discord.js as expected

Having some trouble catching errors in my code. I'm seeing a red line and an expression expected error behind the period after the catch command. Any suggestions? client.on('message', message => { let args = message.content.subs ...

How can I change the behavior of the Enter key in text fields to automatically submit the form, rather than requiring the user to

Utilizing material UI for my component library, I have a compact dialog with a "recover password" button placed within the form. However, upon adding this button, I noticed that pressing the "enter" key in the text fields triggers the onClick event of the ...

Unable to use .click function to choose image within container

Apologies for the lengthy post, but I believe providing all details is essential to understanding the issue at hand. The following code snippet is intended to display the first image in a pop-up box when a user clicks on any of the images shown: <div ...