Question

So here's what I'm trying to do in pseudocode:

array = new Array();
thisObj = new objectTypeOne();
thisObj2 = new objectTypeTwo();
array.push(thisObj);
array.push(thisObj2);

for( i=0; i<=array.length, i++)
{ 
  if( array[i] == objectTypeOne() )
  {
    //do code
  }
 }

I know I could have two different arrays for each object type but that would ruin a lot of my other code which assumes they're both in the same array. (they are pratically same object with slight but vital differences, I suppose I should really have objectTypeTwo derive from other, but that's irrelevant at the moment).

Was it helpful?

Solution

I believe what you're looking for is:

if(array[i] is MyObjectType) {
   //I found an instance of MyObjectType
}

The operator "is" does runtime type analysis and will return true if the object you are testing (in this example, array[i]) is either directly of the type you're comparing to or a subclass (in this example, MyObjectType). You might also want to investigate using typeof. However, try to avoid having a TON of calls like this or calls using "typeof"... looking up type information at runtime is costly in any language.

OTHER TIPS

First correct this i<=array.length to i<array.length. That is the reason for "term is undefined" error.

The solution suggested by @Ascension Systems can be used when you create the instance of diffrent Classes, like

array = new Array();
thisObj = new Student();
thisObj2 = new Employee();
array.push(thisObj);
array.push(thisObj2);

then you can check like

for( i=0; i<array.length, i++)
{ 
  if( array[i] is Student )
  {
    //do code
  }else if(array[i] is Employee){

  }
}

If you are using custom Objects, do like this

array = new Array();
thisObj = new Object();
thisObj.type = "type1";
....
....
thisObj2 = new Object();
thisObj2.type = "type2";
...
...
array.push(thisObj);
array.push(thisObj2);

for( i=0; i<array.length, i++)
{ 
  if( array[i].type == "type1" )
  {
    //do code
  }else if( array[i].type == "type2"){

  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top