My variable calculations just don't add up correctly

I'm struggling to keep track of the count in my var counts within the if statement - can anyone assist me with this?

 Laser.prototype.update = function () {
    //.3
    this.rot += .3
    this.pos.add(this.dir.clone().mult(5));
    this.alive = !(this.pos.x > cw || this.pos.x < 0 || this.pos.y > ch || this.pos.y < 0);
    var counts = 0;
    for (var i = 0; i < asteroids.length; i++) {
        var astPos = asteroids[i].pos.clone();
        astPos.sub(this.pos); //3 impact area
        if (asteroids[i].onscreen && astPos.len() < asteroids[i].sizes[asteroids[i].level] + 10) {
            asteroids[i].hit(this.dir);
            if (counts < 5) {
                this.alive = false;
                counts++;
                //alert("the count is" + counts);
            }
            if (counts > 5) {
                this.alive = true;
                counts++;
                alert("the count is" + counts);
            }
            return counts;
        }
    }
}

Answer №1

Perhaps the scenario where counts == 5 was overlooked, causing it to not increment at all when the count reaches 5. To address this issue, consider modifying the if condition as follows:

if (counts < 5){

            this.alive = false;
            counts++;
            //alert("the count is" + counts);
 }
 else{

             this.alive = true;
             counts++;
              alert("the count is" + counts);

 }

or something similar to handle the case when counts == 5.

EDIT : Additionally, move the return statement outside of the for loop and test again

EDIT2 : Also improve readability by adjusting the if statement like so:

if (asteroids[i].onscreen && (astPos.len() < (asteroids[i].sizes[asteroids[i].level] + 10))) {

for better code clarity

EDIT3: Taking into account the comments below, there are two suggested solutions:

  1. Place the return statement outside of the for loop in this manner:

    if (counts > 5) {
                        this.alive = true;
                        counts++;
                        alert("the count is" + counts);
                    }
                }
            }
           return counts;
        }

  2. Alternatively, declare "counts" as a global variable, increment it within your function as commented, and then return it. In this scenario, the for loop may no longer be necessary and can be removed. Give this a try and provide feedback.

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

How do I transfer a PDF received from a third-party to my client using a REST API on the backend?

After receiving a PDF from a third party, I stored the file on S3. Upon checking the file on S3, I was able to view the PDF without any issues. However, when sending the PDF to the client and verifying it using Postman, an empty PDF is displayed. Below is ...

What is the best way to ensure that this JavaScript code functions properly when dealing with business operating hours

Using this javascript code allows me to check if a business is open based on its operating hours. It's effective for times like 17:00-23:00, but how can I modify it to work for hours past midnight, such as 0:30 or 1:00 in the morning? var d = new D ...

How can I designate class #1 to the left and class #2 to the right within a loop?

Within a loop in Wordpress, two classes, photos and videos, are generated. As new photos or videos are added, they appear below the last div. The issue I'm facing is that I want all photos to be displayed on the left and all videos on the right, but u ...

Using ASP.NET Server Controls to Toggle Textbox Visibility Based on Dropdown Selection

What is the optimal method for displaying or hiding a textbox or an entire div section based on a user's selection from a dropdown menu? I am uncertain if this can be achieved with server controls, so would it require using standard client-side HTML c ...

Retrieving PokéAPI image information

My goal is to display images from the PokéAPI on my app's homescreen when it is opened. However, I am facing a challenge where I need to call 30 different APIs in order to show 30 images. Calling these APIs one after another every few seconds seems l ...

execute a function after submitting the form

I need to implement a function that will be triggered when submitting a form. This function should work for all forms contained within the div with the id "#js_ajax_form". ( The JavaScript code functions properly in Chrome console // Here is the HTML sni ...

Guide on sending a request to an API and displaying the retrieved information within the same Express application

I recently developed a basic express app with API and JWT authentication. I am now attempting to enhance the app by incorporating page rendering through my existing /api/.. routes. However, I am facing challenges in this process. app.use('/', en ...

Utilizing jQuery.ajax to Send an Array of Objects to a PHP Function

In this scenario, an array of objects is represented as follows: rectangle[0].width = w; rectangle[0].height = h; rectangle[1].width = w; rectangle[2].height = h; rectangle[3].width = w; rectangle[3].height = h; ... We need to figure out how to send thi ...

Creating custom validation in Vuetify for password confirmation is essential in ensuring that

While developing a Vue.js template, I encountered a scenario on the sign-up page where I needed to compare passwords during user registration. To achieve this, I implemented a custom validation rule in the code snippet below: <v-text-field label=" ...

Redirect to a specific webpage depending on a certain condition

I currently have a home page set up and now I would like to create a homePlus page that is controlled by a localStorage variable called alreadyShown. The concept is that once the homePlus page is shown for the first time, we will change the value of alread ...

Guide on accessing values from an array of objects in JavaScript/Node.js

I am working with an array of objects that looks like this: const objArray = [{prop: "a", prop2 : "1"}, {prop: "b", prop2 : "2"}, {prop: "c"}, prop2 : "3"] My goal is to extract the property names of the objects in the array, rather than their values. D ...

connecting elements in an object's array to another array within a nested object

Is there a way to iterate through each string value in the imageKeys array and use it to create a URL for each object in the images array within the nested ImageList object, all without changing the original object? const myInitialStateFromParent = { ...

Using AngularJS to add an element to an array based on a specified condition

dashboardCtrl Data app.controller('dashboardCtrl', ['$scope','$rootScope', function ($scope, $rootScope) { //Color $scope.Color = [{ colorname: "Red", number: "(3)" }, { colorname: "Brown ...

Objects hidden in the darkness, utilizing the traditional MeshPhongMaterial

Currently struggling with my shadows issue. Here is a snapshot of the problem I am encountering: https://i.sstatic.net/odnuE.png https://i.sstatic.net/RZitM.png The presence of those lines puzzles me, as the scene should be evenly illuminated! The shado ...

Is there a way for me to include a prefix in the path where Vue pulls its component chunks from?

I recently incorporated VueRouter into my project and encountered an issue with the asset URL not being correct. Instead of displaying www.example.com/js/0.main.js The URL it generates is www.example.com/0.main.js Any suggestions on how to include the ...

React fails to acknowledge union types

I have the following types defined: export enum LayersItemOptionsEnum { OPERATOR, HEADER, } type sharedTypes = { children: string | ReactElement; }; type LayersItemStatic = sharedTypes & { label: string; option: LayersItemOptionsEnum; }; t ...

The regular expression tool is unable to locate and substitute a string that includes parentheses

Seeking help in identifying and highlighting a sentence within a paragraph (found in a textarea). The current method works fine for sentences without parentheses, but struggles with replacing strings surrounded by ""mark"" tags. Is there a way ...

Performing AJAX in Rails4 to update boolean values remotely

Suppose I have a model named Post which includes a boolean attribute called active. How can I efficiently modify this attribute to either true or false directly from the list of posts in index.html.erb using link_to or button_to helper along with remote: ...

Ways to enhance the performance of my websites' backend systems

Greetings! I am currently working on developing backends in ASP.NET 2.0, and have taken steps to optimize the performance by caching images, GZIPing CSS and JS files. The load speed of each option is good, but I am eager for even faster loading times. Alt ...

What steps can be taken once the browser has completed all rendering processes?

I have a large form that functions on older PCs. This form is a component of a thin client system and is implemented using AngularJS to create a Single Page Application. One of the tabs on the SPA includes this form. Upon opening the form, requests are se ...