javascript Problem with push() method

Currently, I am facing an issue with the push() method while trying to add cards to an array in a Deck object. This functionality was previously working fine for me, but recent modifications seem to have disrupted it. (The "testX" prints are included for debugging purposes)

<!DOCTYPE HTML>
<html>
<head>
<style> 
  #myCanvas {
    border: 1px solid #9C9898;
  }
  body {
    margin: 0px;
    padding: 0px;
  }
</style>
<script type="text/javascript">
<!--
//draws the game
window.onload = function() { 
    var canvas = document.getElementById("myCanvas"); 
    var context = canvas.getContext("2d"); 

    //draws the rectangles that will be the card        
    var cardHeight = 125,
        cardWidth = 80;

    context.beginPath();  

    //draws the top row of 5 cards  
    for(var x=0;x<5;x++){
        context.rect(10+(x*(cardWidth+10)),10,cardWidth,cardHeight);
    }

    //draws the bottom row of 5 cards
    for(x=0;x<5;x++){
        context.rect(10+(x*(cardWidth+10)),150,cardWidth,cardHeight);
    }

    //draws the deck
    context.rect(10+5*cardWidth+65,(150-10)/2,cardWidth,cardHeight);

    context.fillStyle = 'white';
    context.fill();
    context.lineWidth = 2;
    context.strokeStyle = 'black';
    context.stroke();   
};


function Deck(){
    //creates the unshuffled deck (loadedDeck) once to make the shuffling process faster
    var loadedDeck = new Array(),
        realDeck;

    this.loadTheDeck = function(){ //method 

        for(x=1;x<=13;x++){ 
            this.loadedDeck.push(x+" Spades"); //<---issue line (all 4 are failing though this is the first)
            this.loadedDeck.push(x+" Clubs");
            this.loadedDeck.push(x+" Hearts");
            this.loadedDeck.push(x+" Diamonds");
        }
        document.write(this.loadedDeck);
    };
    this.loadTheDeck(); //creates the unshuffled deck when the Deck is instantiated


    //resets the deck and randomizes
    this.shuffle = function(){ //method 

        //creates the real deck
        this.realDeck = this.loadedDeck;

        //write shuffle function
    };
    this.shuffle(); //shuffles the Deck when instantiated
}

document.write("test-1");
var myDeck = new Deck();
document.write("test0");
document.write(this.realDeck);
document.write("test1");    
-->
</script>
 </head>
 <body>
<canvas id="myCanvas" height="300" width="600"></canvas>

 </body>
 </html>

To see the code in action, check out the demo link here: http://jsfiddle.net/NfmsR/2/

Answer №1

Executing this line will result in the following:

this.loadedDeck.push(x+" Hearts");

In order to use the this.loadedDeck array correctly, it must be defined as part of the Deck object. If not, an issue may occur:

let loadedDeck = [],
    realDeck;

To rectify this problem, update the declaration to the following:

this.loadedDeck = []; // It's advisable to use [] instead of new Array().
this.realDeck = [];

Yes. Modify realDeck to

this.realDeck</code accordingly since it is being referenced in a similar manner here:</p>

<pre><code>this.shuffle = function(){ //method 

    //creates the real deck
    this.realDeck = this.loadedDeck;

    //write shuffle function
};

Answer №2

When you mention "loadedDeck," it may sound like a property of the "Deck" object, but in reality, it's merely a local variable within the constructor closure.

Try using just "loadedDeck" and see if that resolves the issue. The same advice applies to "realDeck" as well.

this.loadTheDeck = function(){ //method
    for(var y=1;y<=13;y++){ 
        loadedDeck.push(y+" Spades"); //<---problematic line (even though all 4 are failing, this is the first)
        loadedDeck.push(y+" Clubs");
        loadedDeck.push(y+" Hearts");
        loadedDeck.push(y+" Diamonds");
    }

Furthermore, refrain from overusing document.write for debugging purposes. Also, remember to declare variables like "y" with var!!

Answer №3

The Deck instance you are working with, available through the use of this, does not contain a property named "loadedDeck". Instead, loadedDeck is actually declared as a local variable. Feel free to simply delete the "this." prefix.

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

Angular connecting to the count of filtered items

Here's the array I'm working with: [ { type: "hhh", items: [ { "name": "EGFR", "type": "a", "selected": true } ] }, { type: "aaa", items: [ { ...

Make sure to verify the absence of a table entry. Is there a way to validate the 'Items' array if it comes back as null? JavaScript and DynamoDB implementation

I've been trying to determine the existence of an item in my DynamoDB database, but I'm having trouble finding a straightforward solution. I've resorted to using the getItem() operation. According to the documentation, this operation should ...

The Bootstrap slide function encounters issues within the AJAX success callback

Here's the code snippet with a 'slide' event inside an AJAX success call. success: function(data) { $('#my_container').html(data); // Successfully loading #mycarousel into #my_container $('#mycarousel').bind( ...

Enlarge image when clicked

I need help creating a gallery page where users can click on an image to enlarge it, then navigate through the images using arrows on either side. I am not familiar with JavaScript, so could someone guide me on how to achieve this? Also, I would apprecia ...

Issue with NgModule in Angular application build

I'm facing an issue with my Angular application where the compiler is throwing errors during the build process. Here's a snippet of the error messages I'm encountering: ERROR in src/app/list-items/list-items.component.ts:9:14 - error NG6002 ...

What could be the reason for the change event not triggering when using selector.val(1234)?

Similar Question: Why doesn't jQuery textbox.val('xxxx') trigger change event? I am facing an issue with a plugin that should execute when the value of a specific "selector" is updated. While it functions correctly during standard user ...

Tips for aligning multiple identical images horizontally using Javascript

I am attempting to use the following code to display the same image 19 times and then center all of those images horizontally on the page as a whole. However, I have been unsuccessful in getting it to work. var totImg = "large.png"; function prettyHea ...

Open Zurb Foundation Reveal Modal from the bottom of the screen

Struggling to make the reveal modal open from the bottom of the window. Any assistance would be highly appreciated. I've been attempting to tweak the open function with the reveal js, as seen in the original code below. Thank you, P open : function ...

Implementing a stylish background image for a dynamic pie chart using JavaScript

I'm currently developing an application in Rails, and I've integrated a gem called easy_as_pie that allows me to utilize the 'Easy Pie Chart' Jquery plugin () The pie chart is displaying correctly with the following code: $(document). ...

How to dynamically insert an <a> tag using JavaScript or jQuery

index.html <p class="feed-text" style="word-wrap:break-word;margin-top:10px;"><a href="/feeds/view/760">testing Ist part </a><a style="text-decoration:underline;color:blue" href="http://www.youtube.com/watch?v=aqveRU1eAmA" target="_bl ...

Showing off HTML tags within react-json-tree

I have incorporated the following npm package into my project: https://www.npmjs.com/package/react-json-tree My goal is to showcase a json tree in react, but I am facing a challenge on how to include an HTML tag as a JSON value. Are there any alternative ...

How come the method $.when().pipe().then() is functioning properly while $.when().then().then() is not working as expected

I'm still grappling with the concept of using JQuery's Deferred objects, and am faced with a puzzling issue. In this code snippet, my attempt to chain deferred.then() was unsuccessful as all three functions executed simultaneously. It wasn't ...

Utilize a JavaScript array containing numerous objects to transmit information to the Google Tag Manager and populate the Google data

Is there a way to send multiple product information to the Google data layer as an array of objects, rather than just one combined object? I currently have a script that sends all fields in one object, but I need each product to have its own object within ...

Issues with AngularJS have arisen, as it is currently unable to recognize and access variables as needed

As a newcomer to web design and Angular, I am trying to replicate this example, where I consume a RESTful web service and use AngularJS to display the JSON data. However, I'm facing issues with my implementation. Here's how my main.jsp file look ...

When attempting to perform conditional rendering in React using a stateless functional component, I encounter an error stating "Unexpected token, expected ,"

Here is the code snippet: 'use strict' import React from 'react' import { connect } from 'react-redux' import { Panel, Col, Row, Well, Button } from 'react-bootstrap' const Cart = ({ cart }) => { const cartI ...

What is the best way to iterate through this JSON data on an Android device

Is there a way to efficiently iterate through this particular JSON array? [ { "full_name": "Abc Xyz" }, { "full_name": "Def Xyz" }, { "full_name": "Nml Xyz" }, { "full_name": "Jol Xyz" } ] Appreciate any help! ...

What is the best way to isolate a single element within a for loop and exclude all others?

I have implemented a dynamic Ajax call to compare the string entered in the text field (representing a city name) with the "type" value in a JSON array. As I iterate through the elements of the array, I am checking the values associated with the key "type ...

Steps to expand all Bootstrap 5 accordions at once without collapsing any of the currently open ones

I own an accordion How can I expand all accordion items simultaneously by clicking on a single item? Consider the following scenario: Accordion Item #1 is open Accordion Item #2 is closed Accordion Item #3 is closed If we click on item #2 or #3, all ...

Using HapiJs in Node.js to communicate data back and forth with the client

I have client.js and server.js files that are used to send data to my server using ajax. I am able to successfully send the searched username, but on the server side, the domain is being received as undefined. I'm unsure if the issue lies on the clien ...

Issue arises when trying to implement sidebar navigation in Angular with Materialize CSS

Just starting my Angular journey and running into some trouble trying to set up a practical and responsive menu using SidebarNav and Dropdown. I used CLI to install and configure angular2-materialize and materialize-css. To create the menu, I made a comp ...