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

Using router.get with a redirect in Express

Can you directly invoke a router.get(...) function in Express? Let's say I have a router.get('/my-route', function(req, res) { ... });, is it feasible to then, within another part of my code, use res.redirect('my-route'); with the ...

Attempting to create a fixed div at a specific position, however, an unexpected Uncaught TypeError disrupted additional code functionality

Is there a way to make a div stay fixed in place while scrolling, but then unstick at a specific point? I found some code that seemed to work for this purpose, but unfortunately it caused an error that affected other jQuery scripts. The console displayed t ...

tracking scroll position within div on main page

I have a div tag enclosed within a content tag due to the implementation of a masterpage containing the forms and body tags. <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder2" Runat="Server"> <div id="xxx" style="overflow:s ...

Issues encountered when rendering textures from a canvas in Three.js

I've been working on creating a texture from a canvas. I managed to successfully render a blank canvas, but encountered issues when trying to draw an image on the canvas and then render it. This is the code snippet I am currently using: var canva ...

Unable to establish proper functionality of username variables in Node.js chat application

For my latest project, I am developing a chat application in node.js following a tutorial from socket.io. The main objective of the app is to allow users to input their username along with a message, which will then be displayed as "username: message" in t ...

Firestore information does not appear visible

I encountered an issue with my custom hook where I am fetching images from a Firestore collection. Everything was working smoothly until I attempted to retrieve the metadata of the images as well. The problem arose when I included the getMetaData function, ...

Tips for implementing daterangepicker js in an Angular 2 project

I'm currently working on an Angular 2 project and I'm looking to integrate the daterangepicker.js library for a date range picker. If you're not familiar with it, you can find more information about the library here. Here's the HTML co ...

"Using JavaScript to extract a portion of the URL and perform a redirect

I am attempting to extract a specific part of the URL and then redirect to that particular section. Essentially, what I want is for a script to generate a link that will be opened. This link would appear as . My goal now is to extract the portion of the ...

Utilizing the click event with a Bootstrap modal: A guide

I have a PHP script that generates multiple Bootstrap modals, and I want to be able to modify some input fields when the "save changes" button is clicked. The ModalIDs generated are in the format "ModalID0000". However, nothing happens when I click on the ...

I am currently working with a for loop within an object in JavaScript, but there seems to be a problem with one

Here is a function called validator: import validator from "validator"; import isEmpty from "is-empty"; export default function validate(data) { const errors = {}; for (const property in data) { console.log(property); //< ...

Using an external call to trigger the revert method in jQuery UI

My draggable event setup looks like this: $(ids.label).draggable({ containment: ids.wrapper, revertDuration: 100, revert: function(event) { $(this).data("draggable").originalPosition = { top: $(this).data('origionalTo ...

Retrieve targeted information array using jquery

Having an issue with JQuery, my PHP code looks like this: if($record2==0) { if($tmp_curr==$curr) { $reqvendor->inserttmp($json); $json[] = array('stat' => true, 'msg' => ''); //$app['data'] = true; //var_du ...

Choosing a dynamic dropdown option using jQuery and AJAX

I am facing an issue with a select box that is dynamically populated and should display information about a single option. The problem I am encountering is that the browser does not trigger a ':selected' event when I click on any of the options. ...

Unlocking Iframe Mode in CKEditor 4

I've encountered a difference between CKEditor 3 and CKEditor 4. In CKEditor 3, when I call the method CKEDITOR.replace('#textAreaId'), it wraps the editor in an iframe. However, in CKEditor 4, when I call the same method (not inline), the i ...

Typescript is unable to comprehend that the initial item in an array of strings is considered to be a string

Here are the functions I am working with: const transitionGroup = ( propertyName: string, durationMultiple = 1, timingFunction = 'linear', delayMultiple = 0, ): string => { // ...more logic here return [propertyName, duration, tim ...

Issue with hidden sourcemap not loading in Chrome or Firefox during Vite build

Transitioning my react application from create-react-app to Vite has resulted in some unexpected behavior with source maps. To learn more about Vite's documentation on source maps, click here. Initially, I was thinking of using sourcemap: true, but th ...

What is the method to change between input sources in php?

Imagine this scenario: when a user clicks on a specific button, I want them to be presented with either a dropdown list or an input field. This decision would allow the user to choose an existing item or create a new one. <select name="choose[rowId]"&g ...

Vue.js is encountering an issue with receiving the accurate return value from a POST function

I am facing an issue where I am unable to receive the full data that is being sent from the frontend to the backend. Here is an example of the data structure that I am sending: { _id: 64a8a8e9903039edb52ccc4c, productName: 'Vial 2ml(US) Type1&apos ...

What is the process of using observables in Angular to retrieve a number or variable?

While working on an angular service that calls an API and processes a large amount of data, I encountered an issue. I was trying to count the occurrences of each type in the data and send back that count along with the data itself. However, I found that wh ...

Inject CSS into an iframe containing a JavaScript form by iterating over a collection of iframes

My task is to manipulate an iframe (chatbox) once it's loaded on a webpage. This chatbox consists of four iframes, each with a different id that changes with every page load. Since the iframe that needs manipulation is always the last one in the list, ...