- Home /
JavaScript String Question
Rather new to javascript, I am trying to create a two dimensional array and populate with a string that is it's space delineated location within the array. ie Array[2][2] would be "2 2". However I receive the compiler error BCE0024: The type 'String' does not have a visible constructor that matches the argument list '()'. What am I doing wrong?
var mapSizeX = 256; var mapSizeZ = 256;
function Awake () { mapArray = new Array(mapSizeX); for (var x = 1; x <= mapSizeX; x++) {
mapArray[x] = new Array(mapSizeZ); for (var z = 1; z <= mapSizeZ; z++) { mapArray[x][z] = new String (); mapArray[x][z] = x + " " + z; } } Debug.Log(mapArray[2][2]); }
Answer by skovacs1 · Nov 09, 2010 at 07:58 PM
- Arrays are indexed starting at 0. If your code actually did compile, when you ran it, you would get an out-of-bounds error.
- You don't need to call a String constructor (and you can't as per the error). When you assign x + " " + z, it creates a String for you because of your string concatenation. Because your array is non-typed, it would store non-string values if that's what you were actually passing in (you aren't), but if you were passing a non-string object to something expecting a String value, in most cases, it would implicitly call object.ToString() for you so you shouldn't have to worry about that anyways.
This will do what you want:
var mapSizeX = 256; var mapSizeZ = 256;
function Awake () { mapArray = new Array(mapSizeX); for (var x = 0; x < mapSizeX; x++) {
mapArray[x] = new Array(mapSizeZ); for (var z = 0; z < mapSizeZ;) { mapArray[x][z] = (x+1) + " " + (++z); } } Debug.Log(mapArray[1][1]); //0,0 stores 1,1. 1,1 stores 2,2. etc. }
But like Eric5h5 wisely points out, the c# multi-dimensional arrays are better anyways if they don't need to be resized.
Answer by Eric5h5 · Nov 09, 2010 at 08:00 PM
Strings are structs and do not need to be initialized with new, and in fact cannot be. Unless the arrays need to be dynamically sized, however, it would be quite a lot faster to use this for actual 2D string arrays instead of using Arrays of Arrays.
I was trying to avoid using the work around with making a separate c script, but you are right that it's probably the best way. Thanks.
Your answer
![](https://koobas.hobune.stream/wayback/20220613082500im_/https://answers.unity.com/themes/thub/images/avi.jpg)