flavour404
flavour404

Reputation: 6312

How can I work with a multi-dimensional array in JavaScript?

I have a multi-dimensional array, no problem. How do I interrogator one of the arrays in order to ascertain if it actually holds any data? I am working with VS 2008 and what I can see in the debugger is, lets call the element x, is x{...}. However, if I try and use x.length i get the message 'undefined' - so how do I ascertain if the array has nothing in it?

type(x) is returning an object. Here is the constructor code:

function initArray() {
var length = initArray.arguments.length for (var i = 0; i < length; i++)
{ this[i+1] = initArray.arguments[i]; } }

So it should return a .length value, which it isn't!

In the multilevel array, it's the third level down so x = pub[1][8] which should be the target array, but as I said if I then go x.length, or x[].length I get undefined...

Thanks.

Upvotes: 2

Views: 1120

Answers (6)

Nosredna
Nosredna

Reputation: 86216

Are you sure it's an array and not an object? Arrays use [] and objects use {}.

The array's length should be zero upon its definition.

You can check typeof(x) to see if it's undefined.

This is a case where we're shooting in the dark without seeing your code.

Upvotes: 2

Andrew Noyes
Andrew Noyes

Reputation: 5298

The only vector data type in JavaScript that lacks a length property is Object, so you're likely dealing with an object and not an Array.

Upvotes: 0

Chris Pietschmann
Chris Pietschmann

Reputation: 29905

You could use a boolean operation to check it as you mentioned.

var arrayHasValues = false;
if (x.length) { // <-- Will be 'true' if 'length' is not null or undefined
    if (x.length > 0) {
        arrayHasValues = true;
    }
}

if  (arrayHasValues) {
    // Do Something with Array
}

Upvotes: 0

Jeff Meatball Yang
Jeff Meatball Yang

Reputation: 39027

It looks like your object x is not an array at all.

If it were, the length would be zero or positive integer.

It sounds like you might have an object and inadvertently added expando properties.

try this:

for(var prop in x) {
    var p = prop; // set a breakpoint on this line and check the value of prop
}

Upvotes: 1

Chris W. Rea
Chris W. Rea

Reputation: 5501

If it's an array created like "x = new Array();" or "x = [];", then it ought to have a .length property. If it doesn't have a .length property, then you are likely dealing with a null reference (no object) or else you aren't dealing with an array.

Upvotes: 0

Colin
Colin

Reputation: 10638

check if the object is an array first:

function isArray(obj) {
  return obj.constructor == Array;
} 

Upvotes: 0

Related Questions