简体   繁体   中英

Create new objects in for loop - Javascript

I have a page that displays graphs based on the selected criteria. Each graph is a separate instance and needs its own object reference. I have new objects being created within the for loop but how can I access those objects outside that particular 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 need to use chartObject[j] in another function:

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

Obviously j isn't defined in drawDataView , so how can I create new objects within that for-loop and use the variable elsewhere?

Any suggestion is appreciated!

You could just pass j as an extra parameter to the drawDataView function:

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

and call it like this:

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

Update

Because you're not returning anything in the drawDataView function, your array will be filled with undefined . I think you want to add return dataCache; at the end.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM