Search code examples
arraysactionscript-3multidimensional-arrayactionscript

Actionscript, hasOwnProperty() of multidimensional arrays


I'm trying to check wether a key exists in a multidimensional array. The following code is my example:

var tiles:Array = new Array(
                    new Array(4),
                    new Array(4),
                    new Array(4),
                    new Array(4)
                 );
if(test.hasOwnProperty(2)) {
  trace('True');
} else {
  trace('False');

This returns True, as expected since the key 2 indeed exists in the array "test".

However if I try to this on any of the arrays within my array, the code always returns False.

var tiles:Array = new Array(
                    new Array(4),
                    new Array(4),
                    new Array(4),
                    new Array(4)
                 );
if(test[1].hasOwnProperty(2)) {
  trace('True');
} else {
  trace('False');

I was hoping anyone could shed some light on this, what am I missing? Maybe there is another way of doing this check? Any help is much appreciated, thanks! :)

Edit:

Changed my array-definition to this:

var tiles:Array = new Array(
                    new Array('','','',''),
                    new Array('','','',''),
                    new Array('','','',''),
                    new Array('','','','')
                 );

And ofcourse, issue solved! Thanks for the help everyone :)


Solution

  • Your inner arrays don't have any values at position 2, so your results are expected. They have four empty slots.

    For arrays, which are sequential data and not intended as key: value stores, you might find tools specific to arrays make more sense for what you are trying to do, for example:

    if (test[1].length >= 2)
    

    This way, you would get true like you're hoping for.