javascript array filled in an unusual manner

Currently, I am developing an angular application that involves creating a custom array of services called Workbooks, each containing an array of services known as Views. However, while populating the array using a simple for loop, I encountered some unexpected outcomes:

Following the initial iteration, there is one workbook present in the array: Workbook 1

Upon completing the second iteration, two workbooks appear titled "workbook 2": Workbook 2 Workbook 2

With the third iteration: Workbook 3 Workbook 3 Workbook 3

This pattern continues with subsequent iterations. I have included a simplified version of the code snippet below showcasing how the workbooks are created and added to the array:

for (var i = 0; i < 3; i++) {
    var workbook = Workbook;
    workbook.setTitle("workbook " + (i + 1));
    for (var j = 0; j <2; j++ ) {
        var view = View;
        view.setTitle("view " + (j + 1));
        workbook.addView(view);
    }

    workbooks[i] = workbook;

    //this following loop can be utilized to print the array contents as mentioned    
    for (var k = 0; k < workbooks.length; k++) {
        console.log(workbooks[k].getTitle());
    }
}

return workbooks;

The issue arises when the ith workbook is allocated a specific title and placed into the respective spot within the array. How could it happen that when i equals 2, a workbook labeled Workbook 3 gets assigned to indices 0, 1, and 2 simultaneously?

For further information, here is a demonstration on Plunker illustrating the relevant code section from the project. Any input or guidance would be greatly appreciated!

Answer №1

The issue arises from assigning the ith workbook to each spot in the array, which results in them all pointing to the same workbook instance and only updating the title on one. To resolve this, you should change

var workbook = Workbook;

to

var workbook = new Workbook;

Answer №2

For your factory implementation, make sure to create a new object each time the factory is called.

GATapp.factory('Workbook', function () { 
    return function () {
        var title;
        var views = [];
        this.getTitle = function () {
            return title;
        }
        this.setTitle = function (newTitle) {
            title = newTitle;
        }
        this.getViews = function () {
            return views;
        }
        this.addView = function (newView) {
            views.push(newView);
        }
        this.getView = function (i) {
            return views[i].getTitle();
        }
    };
});

Remember to instantiate a new object when using the factory.

var workbook = new Workbook();

Feel free to check it out: Plnkr

Answer №3

First off, let's address an issue:

for (var i = 0; i < 3; i++) {
var workbook = Workbook;
workbook.setTitle("workbook " + (i + 1));

Within this loop, you are constantly recreating the 'workbook' variable and giving it the same name 'workbook X'.

It seems like instead of creating a new workbook each time, you're actually just using the same reference repeatedly, resulting in all workbooks pointing to the same object.

As you go through the loop again, you're only updating the title of this reference, causing both references to update simultaneously.

Try out the following modification and observe how it behaves.

var workbook; // cleaner approach, prevents redeclaration
for (var i = 0; i < 3; i++) {
    workbook = new Workbook; // avoids referencing the same Workbook object
    workbook.setTitle("workbook " + (i + 1));
    for (var j = 0; j <2; j++ ) {
        var view = View;
        view.setTitle("view " + (j + 1));
        workbook.addView(view);
    }

    workbooks[i] = workbook;

    // Utilize this next loop to print the array as specified    
    for (var k = 0; k < workbooks.length; k++) {
        console.log(workbooks[k].getTitle());
    }
}

return workbooks;

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

Breaking free from JavaScript snippet within a PHP function in WordPress

There seems to be an issue with a function within one of the PHP files on a WordPress website. It appears that there may be an error related to escaping multiple quotes and slashes. Here is the specific line of code causing trouble: echo '<script ...

Seeking specific parameter in a JSON array using JavaScript: A guide

Currently, I am working on a project that involves retrieving Facebook news feed data using the graph API. Upon receiving the JSON object, I display it on the page. The "Likes" section is presented as an array of JSON objects like this: data.likes: { ...

The meteorite experienced a crash as startup.js attempted to connect with Mongo

Setting up a Mongo database for a meteor project has been tricky for me. I've created a startup.js file to load the necessary files, but as soon as I start meteor, it crashes. Can anyone lend a hand, please? Here is a snippet from the HTML file: < ...

The Highcharts Range Selector feature may encounter issues when used with multiple series

Currently, I am facing an issue with my highchart/highstock where I retrieve data from a PHP file. The problem arises when I attempt to use multiple series as the RangeSelector Buttons cease to function properly. For instance, in the example provided, the ...

How can I change the color of a designated column in a Google stacked bar chart by clicking a button?

I am in the process of creating a website that compares incoming students at my university across different academic years. We have successfully implemented a pie chart to display data for the selected year. Now, we aim to include a stacked bar chart next ...

Can someone explain why the index call is not reaching the "/" route in Node.js?

When I access the server by going to http://localhost:3000, it displays my index file but does not route to the get function in index.js. I am currently stuck at this point. Below is my app.js file: var express = require('express'); var path = ...

What is the best way to save user-inputted values into an array in shell or bash scripts?

I have a variety of input elements that I would like to store in an array. The number of elements is unknown. For example: one two three four five six The size of the input can vary. I attempted to do it this way: declare -a array read -a array ech ...

Kendo grid in Angular JS is not displaying populated data

I am able to successfully retrieve data from the database, but I am encountering an issue with populating it in a gridview. Below is my code snippet: <div ng-app="app" ng-controller="MyCtrl"> <div kendo-grid k-options="gridOptions" k-rebind ...

Utilizing the reduce() function to simultaneously assign values to two variables from data input

Looking to simplify the following function using reduce(), as the operations for variables selectedEnrolled and selectedNotEnrolled are quite similar. I attempted to use map(), but since I wasn't returning anything, it led to unintended side effects ...

The children's className attribute can impact the parent element

As I work on creating a card object, I envision it with the className .card that is styled in CSS as follows: .card img{position:absolute; width:150px; height:160px} I want only the images inside my div to overlap each other while not affecting the divs ...

Retrieve information from MongoDB and showcase it on the user interface

I am a beginner in NodeJS and server-side technologies, currently working on building a simple app that involves data insertion into a MongoDB database. I am using express-handlebars for this project. While I have successfully saved the data into the data ...

HTML: keeping script for future use in a variable

Is there a way to store a value in one place within an HTML document without the need for a database or PHP? Avoiding the repetition of typing the same value multiple times is the goal. Consider the following scenario: HTML <!-- Desktop --> <di ...

Guide on utilizing two separate collections to store different types of data for an application's users

I am looking to create a database collection similar to {username : "jack", password : "pass"} for storing doctors' login information. I believe I can achieve this during signup by implementing the following code: var Doctor = mongoose.model("doctor" ...

The websocket connection to the production host has encountered issues, while it operates smoothly on localhost within Django

I successfully integrated a websocket connection for real-time updates in my Django application. The issue arises when I try to host the application on a public server, as it fails to connect. I am using Daphne server for hosting. Below is a snippet of my ...

When the clearOnBlur setting is set to false, Material UI Autocomplete will not

I recently encountered an issue in my project while using Material UI's Autocomplete feature. Despite setting the clearOnBlur property to false, the input field keeps getting cleared after losing focus. I need assistance in resolving this problem, an ...

Working with floating point numbers in Node.js with a zero decimal place

NodeJS interprets float values with a zero after the decimal point as integers, but this behavior occurs at the language level. For example: 5.0 is considered as 5 by NodeJS. In my work with APIs, it's crucial for me to be able to send float values w ...

Using AngularJS 1 to create a universal search filter for all values stored in an Array or JSON object

I am currently working with an outdated version of AngularJS (1.x). I have a JSON object containing various key/value pairs. Is there a way to filter based on any of the values in the array? I am looking to implement a global search input field where users ...

Acquiring JSON data within a JavaScript function using PHP

Requesting assistance on reading a JSON value using the code below, to retrieve data based on the $movieID. <script> function bookBTN(x) { <?php $url = 'http://movie.com/movieOne?seatNum=' . x; $jsonURL = file_get_ ...

Tips for triggering the .click() function upon returning to index.html after visiting a different page

I'm in the process of creating a portfolio website where the index.html page features a sliding navigation bar that displays a collection of projects. Each project is linked to a separate work.html page. I would like the sliding nav to automatically o ...

Creating a Server-Side Rendered application from scratch

Currently, we are in the process of developing a Nuxt application using npm run generate and deploying it as a Static Site Generator (SSG). However, an issue has arisen where the application is being built as a Client-Side Rendered (CSR) app instead of Ser ...