Asher
Asher

Reputation: 2774

Checking a 2D Array Bounds in Javascript

I have a 2-dimensional array that I want to check the bounds in Javascript. I prefer doing this without checking each index independently.

For example if my 2d array is...

dataset[row0-1][column+column0]

I really do not want to have to do the following...

if(row0-1 >0)
{
    if(dataset[row0-1].length >= column+column0)
    {
        data = {label : dataset[row0-1][column+column0]};
    }
}

The problem is that I have to first check the row and then check the column. I prefer doing both of these checks with one operation or on one line. Rather then returning an out of bounds error, why doesn't Javascript just return null or undefined?

For example, in a future version of Javascript, wouldn't it be better if we could do this?

if(dataset[row0-1][column+column0] != undefined)
{
   data = {label : dataset[row0-1][column+column0]};
} 
else 
{
    ...
}

Upvotes: 2

Views: 2269

Answers (5)

Fernando JS
Fernando JS

Reputation: 4317

Using the @dmck answers, I use prototype in Array object.

Function:

Array.prototype.CheckBounds = function (x, y)
{
    if (this[x] === undefined)
        return false;

    if (this.length > x && this[x].length > y) {
        return true;
    }

    return false;
}

How to use:

if(myArray.CheckBounds(5,10)) //Check bounds
 {
   //OK
 }else{
   //Out of bounds
 }

Upvotes: 0

ayan ahmedov
ayan ahmedov

Reputation: 391

I do mostly like this: say we have 2d array arr and we need to access an element which isn't there.

var arr = [/*elements*/]
var get = function(x, y) {
  if(!arr[x]) {
      return false;
  }
  return arr[x][y] || false;
}

Upvotes: 0

Bergi
Bergi

Reputation: 664599

You can easily combine nested if-clauses to a one-liner using the AND-operator &&:

if (row0-1 > 0 && dataset[row0-1].length >= column+column0){
    data = {label : dataset[row0-1][column+column0]};
}

although you really should check for the array's length, not (only) greater-than 0. Better:

if (row0-1 > 0 && row0-1 < dataset.length && column+column0 < dataset[row0-1].length)
    data = {label: dataset[row0-1][column+column0]};
}

Upvotes: 0

dmck
dmck

Reputation: 7861

You can write a function to check:

function CheckArrayIndex(x, y) {
    if (dataset.length > x && dataset[x].length > y) {
        return dataset[x][y];
    }

    return null;
}

Then you can use it like this:

if(CheckArrayIndex(row0-1,column+column0) != null){
   data = {label : dataset[row0-1][column+column0]};
}

Upvotes: 2

Wolfman2000
Wolfman2000

Reputation: 153

I think the reason for checking each index independently is because each dimension can have different lengths on each index.

I know C# has Multidimensional Arrays, but Javascript uses Jagged Arrays.

I do not picture this changing any time soon.

Upvotes: 1

Related Questions