Array

patrick

Well-known member
Joined
Dec 5, 2021
Messages
251
Programming Experience
1-3
C#:
var filter = new Array();

for ( var= 0 ; i < dt.length ; i++)
{
    var dec = dt[I].desc;
    filter[dec].push( dt[I].id );
}
Error === cannt read property 'push' of undefined
 
Last edited by a moderator:
That is because when you instantiate an Array directly, you get and array of the base class Object. Object does not have a push() method. In fact l, even the Array class does not have a push() method either. The push() function is a C++ standard library thing, not a C# thing.

Also, please remember to post your code in code tags. I've edited your post to do this your you... Again.
 
You should never be creating an instance of the Array class. If you want an array, create an array of the actual type you want, e.g. string[].

You need to specify the size of an array when you create it. If you need something to grow as you add items, use a collection instead, e.g. List<string>.
 
Since it is posted in Web Forms forums, it is probably Javascript.
 
But this is a C# forum... something is really wrong on multiple levels here. Why ask a JavaScript question in a C# forum?
 
Well, there are some minor logical issue with your code:
Here is the correct code:

C#:
var filter = {};  // Use {} to create an object instead of new Array()

for (var i = 0; i < dt.length; i++) {
    var dec = dt[i].desc;
    if (!filter[dec]) {
        filter[dec] = [];  // Initialize the array if it doesn't exist
    }
    filter[dec].push(dt[i].id);
}


Thanks
 
Back
Top Bottom