jacksantho
jacksantho

Reputation: 391

javascript : In For loop pushing the value into the array variable, but values get appended(push) with undefined

 if (objJson[0].task.length > 0) {

                    var Arrayset = [];
                    var categories = [];
                    var starts1 = [];
                    var ends1 = [];
                    var val1 = [];
                    var val2 = [];

                    for (var i = 0; i < objJson[0].task.length; i++) {

                        var syearval = parseInt(objJson[0].PSDate[i].substr(0, 4));
                        var smonthval = parseInt(objJson[0].PSDate[i].substr(5, 2));
                        var sdateval = parseInt(objJson[0].PSDate[i].substr(8, 2));

                        var eyearval = parseInt(objJson[0].PEDate[i].substr(0, 4));
                        var emonthval = parseInt(objJson[0].PEDate[i].substr(5, 2));
                        var edateval = parseInt(objJson[0].PEDate[i].substr(8, 2));



                       val1=[Date.UTC(syearval, smonthval, sdateval)];

                       val2= [Date.UTC(eyearval, emonthval, edateval)];


                       starts1.push(val1[i]);
                       ends1.push(val2[i]);

                       Arrayset.push({ name: objJson[0].task[i], completed: objJson[0].taskpercent[i], start:starts1[i], end:ends1[i] });


                    }

                    MainLoadChart(Arrayset);
                }

            }

Declared two array variable starts1 and ends1.

For loop when i=0

starts1=[1574035200000] ends1=[1574640000000]

values get added correctly in the array.

same thing, for loop gets iterated (i.e) when i=1 etc

starts1=[1574035200000, undefined] ends1=[1574640000000,undefined]

In starts1 and ends1 array undefined gets added in the array. I tried in all the ways and i am unable to fix to solve this issue.

Upvotes: 0

Views: 49

Answers (2)

as-if-i-code
as-if-i-code

Reputation: 2340

There is a problem with assignment of val1 and val2. You are repeatedly assigning a new array with 1 item to it, that's why there is value at index 0(when i=0) and undefined for index 1, 2,3 .. and so on.

You can actually skip this declaration & assignments of val1, val2 and directly push values to array.

    //val1=[Date.UTC(syearval, smonthval, sdateval)];
    //val2= [Date.UTC(eyearval, emonthval, edateval)];


      starts1.push(Date.UTC(syearval, smonthval, sdateval));
      ends1.push(Date.UTC(eyearval, emonthval, edateval));

Upvotes: 0

Kiran Shinde
Kiran Shinde

Reputation: 5982

When i = 1

Your val1 will have only 1 value in array same for val2 i.e. array will have only 1 element

And you are pushing index value which will be undefined

How about

Instaed of

starts1.push(val1[i]);
ends1.push(val2[i]);

Use

starts1.push(val1[0]);
ends1.push(val2[0]);

Upvotes: 1

Related Questions