Using a constructor function in a for loop

Currently, I am learning how to build a Blackjack game with Javascript on Codecademy.

I'm struggling to figure out what code to write inside the for-loop. The task at hand is to create a "score" method within the Hand constructor. This method should iterate over all the cards in the Hand, add up the values obtained from the "getValue" function call for each card, and finally return the total sum.

If anyone could lend me a helping hand, I would greatly appreciate it. Thank you in advance.

Below is my attempt, involving the relevant code located within the for-loop at the end:

// Card Constructor
function Card(s, n) {
  var suit = s;
  var number = n;

  this.getSuit = function() {
    return suit;
  };

  this.getNumber = function() {
    return number;
  };

  this.getValue = function() {
    if (number >= 10) {
      return 10;
    } else if (number === 1) {
      return 11;
    } else {
      return number;
    }
  };
};

//deal function
var deal = function() {
  var randNum = Math.floor(Math.random() * 13) + 1;
  var randSuit = Math.floor(Math.random() * 4) + 1;
  console.log(randNum, randSuit);
  
  return new Card(randSuit, randNum);
};


function Hand() {
  var handArray = [];
  handArray[0] = deal();
  handArray[1] = deal();

  this.getHand = function () {
    return handArray;
  };
  
  this.score = function() {
    var sum;

    for (var i = 0; i < handArray.length; i++) {
      sum += handArray[i].getValue();
      
      return sum;
    }
  };
};

Answer №1

Here is an example of a function that should do the trick:

this.getTotalScore = function() {
  return cardsArray.reduce( function( sum, card){
    return sum + card.getValue();
  });
};

Answer №2

To calculate the total score, make sure you move the return statement outside of the loop:

this.calculateScore = function() {
  var totalSum;
  for (var j = 0; j < cardHand.length; j++) {
    totalSum += cardHand[j].getValue();
  }
  return totalSum;
};

Answer №3

Problem solved! Your assistance was greatly appreciated.

this.calculateScore = function(){
    var total = 0;
    for(var i = 0; i < handArray.length; i++){
        total += handArray[i].getValue();
     }; 
    return total;
};

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

The values obtained from the previous parameter object of the React setState hook can vary and are not always

In my code, I am using a useEffect hook to update the state with setState. However, I'm encountering some unusual and inconsistent behavior with the previous parameter: useEffect(() => { setCurrentPicturesObject((existing) => { ...

Determine the number of strings that start with the letter "x" and save them in an

I created a regex in String to store JSON Data, and I was able to identify all images in the JSON Data : Pattern pattern = Pattern.compile("<a[^>]*>"); Matcher matcher = pattern.matcher(contentString.toString()); while(matcher.fi ...

Vue.js does not seem to be properly assigning attributes that are declared within the data object array

Trying to get a hang of vue.js and looking to create dynamic product cards using it: This is the snippet from my HTML file: <div id="app"> <card v-for="products in product" :productname="product.productname"></card> </div> Here&a ...

What is the best way to retrieve a single document from MongoDB by using the URL ID parameter in JavaScript?

I'm currently working on a movie app project and have defined my movie Schema as follows: const movieSchema = new mongoose.Schema({ name: { type: String, required: true }, genre: { type: String, required: tr ...

Prepending a string to the key of a JSON object using JavaScript

Is there a way to add 'd:' before the key of a JSON object? Here is the JSON data: "data": { "aa": "value", "ab": "value" } The expected result should look like this: "d:data": ...

The "util" module has been extracted to ensure compatibility with browsers. Trying to use "util.promisify" in client code is not possible

Currently, I'm in the process of scraping LinkedIn profiles with the help of this library: https://www.npmjs.com/package/@n-h-n/linkedin-profile-scraper. Listed below is the code snippet that I am using: <script> import { LinkedInProfileScraper ...

Is it possible for AJAX to update a button's argument?

After successfully using AJAX to extract a data value from a button click, I am now looking to pass this value as an argument to another button on the same page. Is there a way to achieve this seamlessly? Sample code from test.html: <a href="#" onClic ...

Is there a way to make the first Image Element within the div automatically clickable?

Is there a way to set the first image in a div as the default clicked element? I have a div with multiple images and I want the first one to be clicked by default. This is part of a React functional component that serves as a view. <div className=&quo ...

Excessive CPU usage caused by a patch in jQuery dealing with regular expressions

Working on a project developed by an unknown individual has presented some challenges. Without any means of contact with this person, I noticed that the browser's CPU consumption spikes significantly upon loading the page. Upon further investigation, ...

Having issues with creating a poll command for my Discord bot as it keeps throwing the error message: "Oops! TypeError: Cannot read property 'push' of undefined."

Can anyone assist me with my question? I am using discord v11.5.1 Below is the code: exports.run = async (bot, message) => { const options = [" ...

What options are available to enable the user to input information into the v-time-picker component?

I am looking for a solution where users can input digits into the vuetify v-time-picker, while still being able to select the time on the clock. <v-col align-self="center"> <v-menu ref="menuTimeStart" v-model="me ...

Next JS encountered an error - Error [ERR_HTTP_HEADERS_SENT]: It is not possible to set headers after they have already been sent to the

Having crafted a serverless application using next.js, Vercel, and Google Sheets to store customer contact data, I encountered an issue post-deployment. While my application works flawlessly locally, after deployment, I started receiving the following erro ...

Vue.js - experiencing issues with conditional styling not functioning as expected

Can someone help me with an issue I'm having? I've created a button with a heart symbol that is supposed to change color when clicked, but it's not working as expected. This is my current code: <template> <button v-bind: ...

A guide on efficiently storing and retrieving a webpage containing two angular2 components using local storage

I've been attempting to store and retrieve a page containing two angular2 components from local storage using the following code, but the component CSS is not being applied. Here is the code I'm using to save: localStorage.setItem('pageCon ...

Function compilation did not succeed in the module

I've put together a MERN (MongoDB, ExpressJS, React, Node) project using express-generator (express myNewApp). Within a react component, I have implemented this ES6 code snippet: onChange = (event, { newValue }) => { // Line 53 this.setSt ...

Dynamic TypeScript class constructor argument typing determined by user input

I am working on creating a dynamic class that can adapt its argument properties based on a certain value. To illustrate this concept, let's consider a simple example: Imagine I have a class called Customizer, and depending on the value of the mode pr ...

What is the best way to clear an XML or table?

As I delve into learning Javascript, I've been experimenting with different approaches to achieve a specific functionality. I'm trying to implement a button that can toggle or hide XML data in a table. My attempts so far have involved adding anot ...

Processing JSON using PHP and transforming it into an array

I've had limited experience working with JSON in the past, and now I can't remember how to use it with PHP. If there is a script that outputs JSON in this format: { "bunisess":[ "business", "bonuses", "burnooses", "boniness", ...

Is it possible to show more than five buttons in an Amazon Lex-v2 response display?

Here is the sessionState object I am working with: { "sessionAttributes": {}, "dialogAction": { "type": "ElicitSlot", "slotToElicit": "flowName" }, "intent": { "name": &q ...

Receiving a 500 status code upon converting a SqlDataReader into Json format

Getting a status 500 error and not sure where I am going wrong. When I click on the 'Getcustomers' button, the 'GetCustomers' method is called which returns JSON. Script: <script> var MyApp = angular.module("MyApp", []); ...