Steps to add an item into an array and access specific properties of that item within the array:

I'm currently developing a blackjack game using Javascript, and I need to create objects for each card so that multiple cards add up to 10. My challenge lies in adding the values of these objects together when they are stored in an array. Here is the relevant code snippet:

var dealerArr = [];
var playerArr = [];
var dealerTotal = 0;
var playerTotal = 0;
var two = {
  value: 2
}
var three = {
  value: 3
}
// The list continues with values for each card

function calcTotal(arr) {
  var sum = 0;
  for (var object of arr) {
    sum += object.value;
  }
  return sum;
}

while (calcTotal(dealerArr) < 17) {
  // Code logic for selecting random cards and pushing them into the dealerArr  
}

Answer №1

The issue arises from the usage of = instead of == within if conditions.

In JavaScript (and many other programming languages), a single equal sign represents an assignment, whereas double and triple equals are used for comparison.

To rectify the code, consider using the following structure:

var dealerArr = [];
var playerArr = [];
var dealerTotal = 0;
var playerTotal = 0;
var two = {
  value: 2
}
// Rest of the variables declared similarly

function calcTotal(arr) {
  var sum = 0;
  for (var object of arr) {
    sum += object.value;
  }
  return sum;
}

while (calcTotal(dealerArr) < 17) {
  var randomCard = (Math.floor(Math.random() * 13) + 1)
  if (randomCard == 1) {
    dealerArr.push(two);
  } else if (randomCard == 2) {
    // Code for other card values follow
  }
  console.log(dealerTotal)
}

Answer №2

It's right to say that Jonas is spot on - in JavaScript, a single = is used for assignment, while == is for comparison and === is for strict comparison (which involves both value and type).

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

What is the best way to prevent event propagation while still allowing a modal to function correctly?

I have a scenario where I want to prevent a table row (<tr>) from receiving a click event when one of two buttons inside it is clicked. To achieve this, I've added an event handler that stops the propagation of the click event. $(".btn").on(&ap ...

Creating a date in the style of a credit or debit card expiration date

I need to create dates in the format of 'Thru: 12/20' (similar to a credit/debit card expiration date). How can I generate a date in this specific format? new Date().toJSON().slice(0,7).split('-').reverse().join('/') Although ...

Unset the class upon clicking outside the div, but maintain the class unset when the div is closed

I have a div that opens when the question mark icon in the upper right corner of the document is clicked. When clicked, a class is added which transforms the question mark into a close icon. When clicking outside the div, the div closes and the class is re ...

Filtering multiple values from a JSON array in Angular 15, separated by commas

Currently, I am implementing Angular 15 in my project. While I am able to filter a single value from the search box, my goal is to filter multiple values separated by commas. Any assistance on achieving this would be greatly appreciated. FilterPipe impor ...

How to Retrieve the Size Measurements of a 3D Model Using JavaScript

Currently, I am involved in an AR project that utilizes three.js and involves working with various 3D models. One issue I have encountered is the inconsistency in sizes among the models. I aim to have all the models of the same size, which requires setting ...

Tips for replicating input boxes in a while loop

https://i.sstatic.net/iuNIl.png HTML : <table> <tr> <td> <input type="text" name="name[]" value=" echo $ail"> <label >Address</label> <input type="text" name="coun ...

Cannot Properly Import JSX Elements in TailwindCSS and React

I am facing an issue with importing a JSX Element into my main file, App.js. The element I want to load is in a separate file called element.js and contains the following code: const element = () => { return ( <div className="text-gr ...

When Infinite Scroll is integrated into another file with HTML tags stacked on top, it will not load additional posts when scrolling down

I have implemented an Infinite Scroll feature that dynamically loads more data from a database as users scroll to the bottom of the page. However, I encountered an issue when trying to include this functionality in another .PHP file. If I insert any HTML ...

Using Node http-middleware-proxy and integrating it with Express to communicate with Tomcat server

We have set up our Java application (which is spring based) in a Tomcat container, with the UI modules also running in the same environment. When we access Tomcat directly through http://localhost:8080, a login page is displayed and then a 302 redirect occ ...

The AJAX file retrieval function is not functioning

I'm working on downloading a file using ajax, but I seem to be facing an issue. Can anyone help me figure out what's going wrong with the code below? url = "https://firebasestorage.googleapis.com/v0/b/analyst-3206a.appspot.com/o/research_reports ...

Creating Text Transitions with JavaScript in Qualtrics: An In-Depth Guide

Currently, I am creating a survey using Qualtrics and I require various texts that will fade in and out within the same area. The goal is to have text that changes every second, displaying the following: Choose a language Escolha um idioma Elija un idiom ...

Combine all the HTML, JavaScript, and CSS files into a single index.html file

So here's the situation - I am utilizing a C# console application to convert four XML files into an HTML document. This particular document will be circulated among a specific group of individuals and is not intended to be hosted or used as a web app; ...

Sequelize querying using the `WHERE NOT EXISTS()` condition

I am currently working with a many-to-many relationship setup in my database: var Genres = db.define('Movie', { name: { type: Sequelize.STRING(100), allowNull: false }, description: { type:Sequelize.STRING(), ...

Is there a way for me to automatically go back to the home page when I press the back button on the browser?

My ecommerce website has a shopping cart page where customers can purchase products and make payments. After the payment is completed, they are directed to a thank you page. The flow of the website is as follows: Home page => Products => Shopping ca ...

Refresh Browser with Angular UI State Parameters

I'm seeking assistance on an issue I've encountered while using angularjs 1.5.5 and angular-ui-router 0.4.2. Specifically, when refreshing the browser, I face a problem that seems to be implementation-specific. Below is a sample code snippet of ...

In TypeScript version 2.4.1, the fontWeight property encounters an error where a value of type 'number' cannot be assigned to the types of '"inherit", 400'

When attempting to set the fontWeight property in TypeScript, I encounter the following error: Types of property 'test' are incompatible. Type '{ fontWeight: number; }' is not assignable to type 'Partial<CSSProperties>&a ...

What is the process for obtaining a Facebook page ID using the Facebook page name?

Can someone please explain the process of obtaining a Facebook page ID from the Facebook page name? I noticed on this website that it displays the number of likes based on the Facebook page name. If anyone has any insight on how to achieve this, I would ...

"Creating a 3D rotation effect on individual objects nested within other objects using Javascript

In my software, I've created four Physijs.BoxMesh(...) shapes, all nested within an independent object. My goal is to rotate these four physics boxes as a whole, but once they are grouped under the 5th object, they no longer respond to rotation comman ...

What could be causing the abortTransaction() method in mongoose to not function as

System OS: MacOS 10.15.5 NodeJS Version: 10.16.3 Mongoose Versions: 5.8, 5.9 MongoDB Version: 4.0.3 The following code snippet is in question: import User from 'models/user' const session = await User.startSession() session.startTransaction() ...

Refresh the information stored in the spliced array of objects

I've managed to splice the data and now I need to update its object from disabled = true to disabled = false. I have searched for another solution but couldn't find one... Any advice is welcomed. Thank you. This is my dropdown: const newDrop = ...