Assistance needed with JavaScript loops

As a newcomer to JavaScript, I am attempting to create a loop for a fight between two fighters. I have set up an array containing the details of the fighters and linked a button in my HTML to trigger the JavaScript code. The objective is to execute a loop where each fighter's attack damage is deducted from the other fighter's health points, with the outcome of the fight displayed on the HTML page afterwards. However, I am unsure about how to proceed or if I have set it up correctly. Any guidance would be greatly appreciated. Below is what I have implemented so far:

var fighters =  [
{
  "name":"Abdi",
  "HP": 100,
  "DMG": 20,
}
{
  "name": "chriz",
  "HP": 100,
  "DMG": 11,
}

]
function myFunction() {
  for (var i = 0; i < fighters.length; i++) {
    fighters[i]
  }
}

Answer №1

You're doing amazing.

Just a few pointers --

  • The usage of fighters[i] is important as it refers to a specific fighter. Consider replacing it with actual logic like fighters[i].HP++ which would increase their health by one.

  • Make sure to add a comma in your fighters array for proper syntax.

  • You have defined the necessary function, but do not forget to call it. You can call it by adding a line such as myFunction();

Additionally, always remember to output something to understand what's happening! Many people use console.log(), for example, console.log(fighters[i].HP)

(Note: I intentionally avoided providing the exact logic you mentioned as I believe it is part of your homework assignment ;)

Answer №2

function combatSimulation() {

  while (combatants[0].healthPoints > 0 && combatants[1].healthPoints > 0) {
  combatants[1].healthPoints -= combatants[0].damagePoints;
  combatants[0].healthPoints -= combatants[1].damagePoints;
  document.getElementById('CombatResults').innerHTML += combatants[1].healthPoints ;
  document.getElementById('CombatResults').innerHTML += combatants[0].healthPoints;
}

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

Modify the background color when hovering using jquery

In order to have buttons with variable colors and a different hover color, I have to apply inline CSS. Since the hover color cannot be added using inline CSS, I need to use JavaScript. I attempted to achieve this using the .hover() function, but the colors ...

When working with angular.js and angular-sanitize.js, the src attribute is removed from JSON HTML data

I'm new to Angular and I'm really enjoying learning how to work with it. Currently, I have a simple JSON file that contains text structured like this: "gettingstarted":{ "title":"Getting Started", "content":"<img ng-src='i ...

Unexpected website icon shows up in my Node.js project

As a newcomer to working with the backend of Node.js, I'm facing an issue while trying to integrate favicons into my project using RealFaviconGenerator. Despite following the instructions provided, the favicons are not showing up on either my developm ...

Web-based client services

Context: An HTML file I'm working with takes in multiple parameters and utilizes JavaScript to dynamically render the content. The page pulls data from various local XML files for processing. For instance, accessing service.html?ID=123 displays info ...

I require assistance in troubleshooting and repairing my HTML and JavaScript code

I am working on creating a feature where users can input their upcoming birthday date and receive an alert showing how many days are left until then. However, I encountered an issue where the alert displays NaN (Not a Number) before the birthday is entered ...

Utilizing a Node.js web server in conjunction with an Apache Cordova Application

I have created an innovative Apache Cordova Application that leverages a Node.js web server to retrieve data from a web API, enabling the JavaScript-based project to utilize the information obtained from the API. Is there a method to integrate this Node w ...

Time when the client request was initiated

When an event occurs in the client browser, it triggers a log request to the server. My goal is to obtain the most accurate timestamp for the event. However, we've encountered issues with relying on Javascript as some browsers provide inaccurate times ...

What is the counterpart of the JavaScript transport.responseText in jQuery's Ajax requests?

I'm currently in the process of converting my JavaScript Ajax request to jQuery's ajax. Here is an example of my existing JavaScript Ajax code: new Ajax.Request(url, { method: 'post', onSuccess: function(transport) { ...

How can the checkbox be checked dynamically through a click event in Angular.js or JavaScript?

I want to implement a functionality where the checkbox gets selected when a user clicks on a button using Angular.js. Here's an example of my code: <td> <input type="checkbox" name="answer_{{$index}}_check" ng-model=&q ...

Stop removing event triggers when the close button on toastr is clicked

Incorporating toastr.js into my application has presented a unique challenge. When a user submits a form, I want to display a toast notification and provide them with a brief window of time to close the toast by clicking a button before sending the data to ...

Issues with basic calculator implemented in HTML

Recently, I've been dabbling in HTML. My goal is simple - to create a form where users can input two numbers, add them together, and see the result in one of the input fields. Here are the two input fields: <input type="text" id="Nu ...

Ways to parse a json document in vue.js

As a novice in web development, I am currently working with vue-cli3.0 and a local server. <template> <div> </div> </template> <script lang="ts"> import { Component, Prop, Vue } from 'vue-property-decorator&apos ...

Controlling data in Firebase collection using Vuex and Vuexfire

I have a question about using Vuexfire to import data from Firebase in Vuex. const state = { ricettario: [] // contains all recipe objects } const actions = { init: firestoreAction(({ bindFirestoreRef }) => { bindFirestoreRef('rice ...

The execution of my JavaScript code does not pause for the completion of an ajax request

I'm currently working on a register validation code in JavaScript. One of the key aspects checked by the validation function is whether the email address provided by the user already exists in the database. To handle this, I'm implementing ajax, ...

Javascript onclick events failing to toggle video play/pause functionality

In my website, I have background music and a background video (webm format) embedded. I am facing an issue with making play/pause buttons in the form of png images work for both the video and the music. The background music is added using the embed tag wi ...

req.user and Is Authenticated are never true

Working on a project using react in conjunction with express.js (within router/user.js) router.get("/", function (req, res) { console.log("this is u" , req.user) console.log(req.isAuthenticated()); if (req.user) { res.json({ user: req.user }) ...

Is there a way to utilize Babel with Webpack while keeping the original folder structure of the source code intact?

I am currently working on a project that has a complex hierarchy as shown below: -src/ -app.js (interacts with server-side code only) -server/ -models/ -routes/ ... -client/ -views/ -scss/ - ...

The $routeProvider is unable to load the view specified in ngRoute

I am currently in the process of implementing ngRoute into my application, but I am facing challenges with getting it to function properly. To showcase my efforts, I have developed a basic app. index.html: <!DOCTYPE html> <html ng-app="tester"& ...

The controller failed to return a value when utilizing the factory

I am attempting to pass a value from my view to the controller using a function within the ng-click directive. I want to then use this value to send it to my factory, which will retrieve data from a REST API link. However, the value I am sending is not ret ...

Two controller files causing conflict with ng-click functionality in partial view

Currently, I am developing a project using MVC4 with angular JS and implementing ng-include to incorporate a partial view within my main view. I have encountered an issue when attempting to click a button located in the partial view. In my setup, there ar ...