- Home /
array and 2d array comparison in javascript problem
I have a function that has an array (String) and 2d array variables (gridMapData and gridMap respectively).
I've spent a lot of time debugging this script tonight and as far as I can tell with exception of performing comparisons on the 2d array as shown below, all other operations I am performing on the 2d array (in this function only assignments and Debug.Log prints).
The below snippet from the script illustrates that a character comparison in a while loop against the array (string) works fine, but I never enter the the if statement when performing a comparison against the 2d array. Performing a Debug.Log shows that gridMap[row,col] in fact == "B".
... // EDIT - I left out how they are declared; gridMapData is actually declared a String, but // I still do not understand why this will not work.
var gridMapData : String = gridMapFile.text; gridMap = new Array (gridSizeRow); gridMap[row] = new Array(gridSizeCol);
... while ((gridMapData[num] == "\n")||(gridMapData[num] == "\r") )
{
// works fine
}
...
if ((gridMap[row][col] == "B"))
{
// never enters
}
...
Debug.Log(gridMap[row][col]); // prints out a "B"
...
Basically, is there anything peculiar about 2d array comparisons in Unity javascript?
Answer by Eric5h5 · Jan 01, 2011 at 06:07 AM
You should use an actual 2D String array, not dynamic arrays, which require casting and are slow. Better yet, something more efficient than strings, such as chars or ints. You can make a 1D array behave like a 2D array using simple math, which is the most efficient, though actual 2D arrays in Javascript can be initialized with this, which are slightly less efficient but usually easier to understand in code.
Eric, thanks for the advice! I'll put some thought into this for optimization.
Answer by jrbailey1977 · Jan 01, 2011 at 04:33 AM
My last edit cued a suspicion that I may have to type cast the gridMap[row][col] to a String before doing a comparison to "B".
After trying different methods to type cast (the syntax is a bit counter intuitive to this C/C++ programmer) all resulting in compiler errors, I came across the ToString() member function for the int class. It works for Array too, though I couldn't find it in the reference material.
This may not be the best way to do this, but it works -
if (gridMap[row][col].ToString() == "B")
{
// now enters the statement correctly
}