Generating fresh instances in for loop - JS

I am working on a page that showcases graphs based on selected criteria. Each graph requires its own object reference, and I am creating new objects within a for loop. However, I'm facing the challenge of accessing those objects outside of that specific function.

var chartObject = new Array();

function runInit () {
$(document).ready(function(){
    $("#submit").click(function() { 
        $("#pointList :selected").each(function(){
            selectedValues.push($(this).val()); 
        });

        for(var j = 0; j < selectedValues.length; j++)
        {
            chartObject[j] = new Object();

            var charts = [];

            charts.push( drawDataView( demos[demo] ) );

            chartObject[j].allDataLoaded = function( ) {
                //more code             
            };
        }
    }); 
});
}

I now need to utilize chartObject[j] in another function:

function drawDataView ( demo ) {
    var dataCache = new DataCache( chartObject[j], dataSource );
}

However, as j is not defined in drawDataView, I am at a loss on how to create new objects within the for-loop and still use the variable elsewhere.

If you have any suggestions, they would be greatly appreciated!

Answer №1

If you want to include the variable j in the function drawDataView, simply pass it as a parameter:

function drawDataView(demo, j) {
    var dataCache = new DataCache( chartObject[j], dataSource );
}

Then, when calling the function, make sure to pass the value of j like this:

charts.push(drawDataView(demos[demo], j));

Note:

Remember to add return dataCache; at the end of the drawDataView function if you want to avoid filling your array with undefined.

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

There was an unexpected error: Unable to access the 'bool' property of an undefined object

{ "name": "unique-react", "version": "2.0.1", "private": true, "scripts": { "start": "webpack-dev-server --hot --port 3002 --open --inline", "build": "cross-env NODE_ENV=production rimraf dist && webpack", "package": "webpack -p ...

Learn how to pass an id from the query parameters to the getInitialProps function in Next.js

Looking to create a basic website that displays content from a database? Utilizing the getInitialProps function from Next.js documentation can help with server-side rendering: https://nextjs.org/docs/api-reference/data-fetching/getInitialProps#getinitialpr ...

Event listeners can only be removed within the useEffect hook

I have encountered an issue when trying to remove an event listener added inside the useEffect hook. The listener is set up to run once after the first rerender, thanks to the empty array passed as the second argument in the useEffect call. I attempted t ...

Utilizing the MEAN stack to establish a connection with a simulated data collection

Currently, I am diving into the world of M.E.A.N stack development. As part of my learning process, I have successfully set up a test page where Angular.js beautifully displays and re-orders data based on search criteria. To challenge myself further, I dec ...

A guide on incorporating a customized Google map into your website

Recently, I utilized the Google Map editing service from this site: https://developers.google.com/maps/documentation/javascript/styling This link provided me with two things: 1. A JSON code 2. The Google API link However, I am unsure about how to incorpo ...

What is the best way to determine the number of queryClient instances that have been created?

Currently, I am managing a large project where the code utilizes useQueryClient in some sections to access the queryClient and in other sections, it uses new QueryClient(). This approach is necessary due to limitations such as being unable to invoke a Reac ...

Observing the element with a directive

I am working with the following code: angular.module("Test", []) .directive("testDirective", function () { return { restrict: "A", scope: { model: "=" } link: function(scope, element) { scope.$watch(function () { elem ...

Error: Property 'blogCategory' is unreadable because it is undefined

Having trouble rendering blog posts from a json file in React const BlogPost = (props) => { const [post, setPost] = useState({ id: "", blogCategory:"", blogTitle:"", postedOn:"", ...

ng-repeat not functioning properly with custom tabs

Everything was working perfectly until I added ng-repeat to the content <ul> <li ng-class="{active:tab===1}"> <a href ng-click="tab = tab==1 ? a : 1">Tab1</a> </li> <l ...

What steps do I need to take to integrate Twilio's SMS service into an HTML document?

I have been searching for solutions using php and node.js (which is a derivative of js, so it should work), but I came across this library: <script type="text/javascript" src="//media.twiliocdn.com/sdk/js/client/v1.4/twilio.min.js"></script> ...

Using Vue with Firebase to fetch a specific range of data starting from a particular record and ending at the

I am looking to retrieve all records from a certain record to the very last one in my database. ref.orderByChild("date").equalTo("19/11/2020 @ 19:50:29").on("child_added", (snapshot) => { console.log(snapshot.va ...

Receiving a `combined` error when updating Meteor isopacket - sourcemapConsumer.destroy function is not recognized

Whenever I attempt to update or create a project using Meteor version 1.9 and above, I encounter the following error: Errors prevented isopacket load: While loading isopacket `combined`: C:\Users\USER\AppData\Local\.meteor\p ...

Setting the font size for the entire body of a webpage globally is ineffective

Technology Stack: Nuxt.js + Vuetify.js Problem: Unable to set global body font size Solution Attempt: I tried to adjust the body font size to 40px in ~/assets/style/app.styl: // Import Vuetify styling ...

Transforming a redux form onSubmit function into a promise-based structure

One of my goals is to promisify the onSubmit handling in my submitForm for redux form. You can find a similar example here. submitForm = () => { return this.props.submituserForm() .then(() => { console.log('test') }) ...

What is the best way to extract "true" values from an array and store them in a new array during iteration?

I am currently enrolled in a Codecademy course and I am facing a roadblock. My main goal is to gain a solid grasp of JavaScript. The current task at hand is as follows: "There is an array of unnecessary words. Your goal is to iterate over the array and fi ...

Encountering Issue: Exceeding the number of hooks rendered in the previous render cycle

Every time I load my Nextjs page, an error message displays: "Error: Rendered more hooks than during the previous render." I attempted to fix this by adding if (!router.isReady) return null after the useEffect code. However, this caused a problem where th ...

What is the best way to incorporate setTimeout in a loop using Coffeescript?

window.onload = -> boxOrig1 = 10 boxOrig2 = 30 canvasW = 400 canvasH = 300 ctx = $("#canvas")[0].getContext('2d'); draw = (origin,dimension) -> ctx.clearRect(0, 0, canvasW, canvasH) ctx.fillStyle = 'rgb(200,0 ...

Combining AngularJS, D3, and JQuery on a single webpage can pose challenges, specifically with D3's ability to accurately read DOM dimensions

I am encountering an issue with my webpage not loading properly. I have structured it using a simple header-body-footer layout in html5 and CSS3. +----------+ | HEADER | +---+----------+---+ | BODY | +---+----------+---+ | FOOTE ...

JavaScript Regular Expression that identifies commas enclosed within quotation marks

I am attempting to parse a text-based log file in the following format: type: 'click', category: 'REFRESH_DOOR', desc: 'clicked refresh from door 0124', site: 'mysite', pathname: '/load_areas/all/doors&apos ...

The Nestjs cronjob is having trouble accessing the injected service

After setting up a cronjob to call a service from another module, I encountered an issue where the console logged items were displaying correctly when running the method manually from the endpoint. However, once I added back the cronjob decorator, the serv ...