Determination of the sum in an array

I'm currently facing an issue with calculating the total numbers in an array. Whenever a new value is added to the array, the total should be automatically updated on the view. However, I'm encountering an undefined error during this process.

var bowlingApp = angular.module('bowlingApp', []);


// Function to add bowling points to the score
  bowlingApp.controller('bowlPoints', function ($scope){
    $scope.bowlPoints = []


    $scope.addBowlPoints = function() {

        if ($scope.bowlPoints.length  < 10) {
            $scope.bowlPoints.push($scope.enteredPoints);
        }
        else {
            alert("Thanks for playing");
        }
    };

  // Function to calculate the total of bowling points
  $scope.total = function() {
    var total = 0;
    if ($scope.bowlPoints < 300) {

    for(var i=0; i < $scope.bowlPoints.length; i++) {
      total += $scope.bowlPoints[i].amount;
    }
    return total;

    };
    };
});

Answer №1

When encountering an error message in a JavaScript console, such as in Chrome, it is crucial to click on the message to pinpoint the exact location of the error.

An undefined error often occurs when attempting to access a property of an object that is not defined. For instance, if $scope.enteredPoints lacks the amount property, then referencing $scope.bowlPoints[i].amount will trigger an undefined error.

I highly suggest utilizing a web browser's JavaScript console for debugging purposes as it simplifies the process significantly.

Answer №2

What purpose does it serve?

if (scope.bowlPoints < 300) {

Is there a way to retrieve the value or size of an array indirectly without explicitly using .length? Check out this example in JSBin where only pure JavaScript is used, no Angular involved. It might provide some insight for you ;-)

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

Exploring Angular's Implementation of D3 Force Simulation

Looking to incorporate a d3 force simulation in my Angular app. I have a run method that initializes and sets simulation options, as well as a ticked method that updates the simulation on each tick. However, I've encountered a few problems with this s ...

"Placement of script tag within the body and the function of the appendChild method

What do you think will happen in the example provided below? The majority of current browsers (such as Firefox 5, Chrome 14, Opera 11.50) will place the iframe above the text. Is this behavior standardized or just a common practice that could potentially ...

Is there a type-safe alternative to the setTimeout function that I can use?

When running my tests, I encountered an issue with the setTimeout method making them run slower than desired. I initially attempted to address this by using "any" in my code... but that led to complaints from eslint and others. Now, I have implemented a ...

The presence of a backslash is preventing the state from transitioning to '/{username:[a-zA-Z0-9]{3,20}}' within the AngularJs UI-router

In my abstract root state named 'site', the empty URL ('') contains two child states: 'profile' and 'home'. The URL for home is '/', while the URL for profile is '/{username:[a-zA-Z0-9]{3,20}}'. I ...

jQuery ajax response html not being updated in div on webpage

I have been struggling with this issue for days and I can't seem to find a solution. My goal is to update a link on a web page with a new file. Even though the post request and new file are visible in the Google Chrome development network, the actual ...

Exploring the depths of async/await within ExpressJS fetch operations

So far, my API-middleware code is functioning properly. I am being cautious to avoid any blocking calls in my express server, which is why I have implemented a function containing asynchronous fetch calls. I'm wondering if this extra step is necessar ...

What is the best way to retrieve the most recent value in a MongoDB aggregation?

In my collection, some documents have a status field while others do not. However, all documents contain a data field. I am trying to construct a query that retrieves the most recent values for both fields. The issue arises when using the $last operator, a ...

Angular JS: Saving information with a promise

One dilemma I am facing is figuring out where to store data that needs to be accessed in the final callbacks for an http request. In jQuery, I could easily handle this by doing the following: var token = $.get('/some-url', {}, someCallback); tok ...

Does the PHP include function act as an HTTP request?

After coming across an article highlighting the negative impact of using excessive HTTP requests on server speed, I started wondering about the performance implications of PHP includes. Specifically, I'm curious if sending 4 AJAX requests compared to ...

Attempting to showcase PHP print statement within HTML using JSON

I want to showcase two PHP echo messages from a different PHP file on my HTML body page. I aim for the echo message to appear when I click the submit button, without being redirected to the PHP page. To achieve this, I need to establish a connection betwe ...

combining the package.json files of the client and server into a single file

I need assistance with merging server-side code (in nodejs) and client-side code (with react) into a single package.json file. The server file is located in the project root directory, while the client-side code resides in the /client folder along with oth ...

Is it feasible to customize the appearance of native scrollbars in GWT without the need for custom scrollbar definitions or the use of ScrollPanel or CustomScrollPanel?

After encountering an issue with a page jumping due to the appearance of a vertical scroll bar, I have decided to always display the scroll bar by applying html { overflow-y: scroll !important; }, instead of using a script to monitor and adjust window/docu ...

The Radio button and Checkbox values are causing an issue where the Radio button is continuously summing upon clicking without a limit. Why is this happening? Check out

I'm currently stuck in a function and believe it would be helpful for you to guide me along the correct path. My goal is to sum the values of checked boxes with the values of checked radio buttons. However, the radio values are continuously accumulat ...

Encountering the error message "Unable to access /" on the browser when using express router

Just started working with the express Router for the first time. Here is my route.js: var express = require('express'); var router = express.Router(); router.get('/', function(req, res) { res.send('home page'); }); module.e ...

Issue with Twilio's sendMessage function: it is not successfully delivering messages to every value within

I am encountering a problem with Twilio failing to send a message to all the values in an array. var index; var a = req.body.numbers; console.log(a); if (req.body.numbers.indexOf("undefined") > -1) { console.log("No numbers stored"); } else { for ...

Modifying element size using jQuery causes issues with maintaining a 100% height

I am facing an issue with a sidebar that is styled using the following css properties: background:#164272; position:absolute; left:0px; top:70px; width:250px; height:100%; When I use jQuery to display a table that is initially hidden and on ...

Preventing toggle from altering the width of the side navigation bar

Is there a way to prevent the width of the side bar from changing when toggling the top level items in the side nav bar, especially if the sub navigation items are wider? Click on 'Click me' in the side nav item to see what happens. Check out th ...

Combining Express.js-REST-Endpoint with a Meteor Application

I'm facing a bit of a challenge here: I am currently in the process of developing a feature-rich application using Meteor. However, I also need to provide some functionality as a REST-Service for automation purposes (another application should be able ...

In Angular, when a promise returns an "undefined" value, how does this interact with .NET

When I execute this code snippet, I am encountering an issue where the response returned is "undefined" instead of the expected value. Here is the code in question: $scope.SameNameFunction = function() { var payload = { itemname: $scope.EventD ...

The CSS class is not properly implemented in the React component

I value your time and assistance. I have spent many hours trying to solve this issue but seem unable to reach a resolution. Here is the React component in question: import styles from './style.scss'; class ButtonComponent extends React.Compone ...