Home > Software engineering >  How to Pass an Unknown Number of objects as arguments into JavaScript Function and at last call the
How to Pass an Unknown Number of objects as arguments into JavaScript Function and at last call the

Time:08-12

I implemented a Javascript function ('setData()') and using another function ('getDataSet(data, id)') it creates the final code. getDataSet(data, id) will be called any number of times and gathering all the data sets, setData() function will be create the chart.

    function getDataSet(data, id){
        //data is a object and name is a element ID
        //do something
    }

    function setData(){
        var chartName;
        var x = new Array;
        for (var i = 0; i < arguments.length; i  ) {
            if (i != 0) {
                console.log(arguments[i]);
                x.push(arguments[i]);
            }
            else{
                console.log(arguments[0]);
                chartName = arguments[0];
            }
        }
    }

When i use as follows it works.

setData("viewPoint", getDataSet(x, 'step1'), getDataSet(y, 'step2'), getDataSet(z, 'step3'));

But the number of calls to getDataSet(data, id) function will be change, according to the number of data sets. Number of arguments to setData() function will be change. There for I implemented showCharts() function as follows.

    //Main function
    function showCharts(){ // <- Not working function

        var objects;

        // Run an array to retrieve data and using them need to call getDataSet()
        // finally add their return values as arguments into setData()

        objects  = getDataSet(data, id)   ","; // <- create data sets separatly

        setData(objects);   // <- show all data sets in one chart
    }

But still can't figure out how to Pass an Unknown Number of objects as arguments into showCharts() function. Please help me.

Here is the real code. Line #132.

CodePudding user response:

you can use

showCharts(...values)
{
    //values will be an array of the variables you passed that you can use
}

CodePudding user response:

I think you may significantly simplify if make a parameter which accepts an array for setData function:

    function showCharts(){
        let arr;
        arr.push(getDataSet(data, id))
        setData(arr);
    }

    function setData(array){
        var chartName;
        var x = new Array;
        for (var i = 0; i < array.length; i  ) {
            if (i != 0) {
                console.log(array[i]);
                x.push(array[i]);
            }
            else{
                console.log(array[0]);
                chartName = array[0];
            }
        }
    }
  • Related