Add a variable to an existing array

As a beginner in the world of programming, I usually rely on online resources to solve my coding problems. However, this time I'm facing an issue that I can't find the solution to online. I have been trying to push a variable into an array and then checking if it actually made it into the array by using console.log. But instead of seeing the names of the variables I pushed in like "card_Fireball" or "card_Waterbolt", all I see is [Card, Card]. The code snippet I am working with is as follows:

var Deck = [];

function Card(name, type, cost, points, damage, heal){
    this.name = name;
    this.type = type;
    this.cost = cost;
    this.points = points;
    this.damage = damage;
    this.heal = heal;
}

var card_Fireball = new Card("Fireball", "spell", 2, 1, 3, 0);
var card_Waterbolt = new Card("Waterbolt", "spell", 2, 1, 3, 0);

Deck.push(card_Fireball);
Deck.push(card_Waterbolt);

console.log(Deck);

While I believe the solution to this problem might be simple, my lack of experience as a beginner programmer is making it hard for me to figure out. Any help would be greatly appreciated! Thank you so much!

Answer №1

All your actions are on point, simply switch out the console.log with this:

console.log(JSON.stringify(Deck));

Answer №2

To access the names of the cards, simply use "Deck[x].name", where x represents the index of the card within the Deck array.

If you want to retrieve all the card names:

for(i=0;i<Deck.length;i++){
    console.log(Deck[i].name);
}

If your cards are named in a similar way as shown in the example, you can also retrieve variable names using this code snippet:

for(i=0;i<Deck.length;i++){
    console.log('card_' + Deck[i].name);
}

Answer №3

If you are looking to retrieve an array of the variable names that have been used, they may be lost along the way.
To collect an array of the names or any other property, consider creating a new array and adding each value to it.

var variables = [];
Deck.map(function(item) { variables.push(item.name) })
console.log(variables);

Output:

["Spark", "Ice Shard"]

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

Retrieving array from input name to store data (PHP)

I am in the process of revamping a form that previously used variables with numerical values instead of an array for the names and ids in the input elements (e.g. agency1, agency2, agency3...) I have considered using the following code snippet: for ($i = ...

In Ruby, I am tasked with finding the pair of adjacent integers in a given array that has the maximum product

This little game in the arcade section of codesignal.com is really giving me a tough time. Let's tackle the challenge: Find the pair of neighboring integers within an array that has the highest product, and return that product. For example, if input ...

Using jQuery to dynamically format a date with variables

Looking to properly format a date for use in a compare function to sort data $(xml).find("item").each(function () { var dateText = $(this).find("Date").text(); var year = dateText.substr(0,4); var month = dateText.subst ...

Postpone the processing of a message in the Service Bus Queue until a specific time using NodeJS

Despite trying multiple tutorials, I have been unable to achieve the desired result so far. Currently, my setup involves a nodejs app that sends messages to the Service Bus Queue and another nodejs app that continuously polls it. The goal is to schedule a ...

The PHP echo function is unable to properly display the values when comparing two arrays

I am trying to extract and compare values from two arrays using PHP. Below is the code that I have written: $maindata=array(array('id'=>3),array('id'=>7),array('id'=>9)); $childata=array(array('id'=>3), ...

What could be the reason for the absence of a second alert appearing?

I have a small application that validates email addresses for the correct elements, but it's not displaying the confirmation message. $(document).ready(function(){ $("#sendButton").click(function(){ var name = $("#name").val(); ...

Is it possible to convert data from an SD card into an array for use with an Arduino

I have some data stored in a text file on an SD card, and I need to convert it into an array in Arduino. The data consists of 270 integers, each one on a separate line. 122 50 255 0 96 My goal is to create an array of size 270 in Arduino so that I can m ...

Showing off map positions on D3 using data from a JSON array

I have received a JSON response containing coordinates from PHP in the following format: {"All":[{"longitude":"36.8948669","name":" Manyanja Rd, Nairobi, Kenya","latitude":"-1.2890965","userID":"1"}, ...]} Next, I am processing it using JavaScript as sho ...

Utilizing React Hooks and Firebase Firestore onSnapshot: A guide to implementing a firestore listener effectively in a React application

SITUATION Picture a scenario where you have a screen with a database listener established within a useEffect hook. The main goal of this listener is to update a counter on your screen based on changes in the database: (Utilizing the useEffect hook without ...

Is it possible to control the visibility of content in HTML based on the current time of day?

Is it possible to display specific parts (divs) on a local site during specific times of the day? If so, how can this be implemented? Thank you. Here is an example of a simple page: <!DOCTYPE html> <html lang="en> <head> <title&g ...

Freshening up the data source in a Bootstrap Typeahead using JavaScript

I'm trying to create a dropdown menu that displays options from an array stored in a file called companyinfo.js, which I retrieve using ajax. The dropDownList() function is called when the page loads. function dropDownList (evt) { console.log("dr ...

Node.js request body is not returning any data

UPDATE: @LawrenceCherone was able to solve the issue, it's (req, res, next) not (err, res, req) I'm in the process of building a MERN app (Mongo, Express, React, Node). I have some routes that are functioning well and fetching data from MongoDB. ...

AngularJS animation fails to activate

I've been working on a simple AngularJS application and I'm trying to add animations between my views. However, for some reason, the animation is not triggering despite following the tutorial on the AngularJS website. There are no errors in the c ...

Trouble with formatting credit card numbers in Vue.js

My payment gateway component includes a feature where selecting credit card triggers the _formatCreditCard method to format the credit card number like this: 4444 2442 4342 3434 This is the function in question: _formatCreditCard: function() { var n ...

Express Vue Production Problem

I've been attempting to implement SSR in my Vue app, and to achieve this I've incorporated the vue-plugin-ssr extension. To run it with express, I created a new file named server.mjs containing the following code: import express from "expres ...

What could be causing the error in sending JSON data from JavaScript to Flask?

Check out this cool javascript code snippet I wrote: <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script type=text/javascript> $(function() { $.ajax({ type: 'PO ...

Change the controller's classes and update the view in Angular

In my angular application, I have a popup window containing several tabs. These tabs are styled like Bootstrap and need to be switched using Angular. The code for the tabs is as follows (simplified): <div class="settingsPopupWindow"> <div> ...

Determine the total number of string elements within a string array using the C programming language

char* names[]={"X", "Y", "Z"}; How can the total number of strings in the array be determined? In this instance, the output should be 3. ...

Creating interfaces for applications that are driven by events in JavaScript

When it comes to designing an application, traditional UML Class diagrams may not always be useful, especially for programs that do not heavily rely on classes. For instance, in a JavaScript application that is mainly event-driven, where you listen for eve ...

Struggling to fill in fields using express and Mongodb

I am facing an issue with populating the fields of two models, Post and User. const PostSchema = new Schema({ text: { type: String }, author: { type: mongoose.Schema.Types.ObjectId, ref: 'user' } }) cons ...