Skip to content Skip to sidebar Skip to footer

Checking For A Numerical Index In A Javascript Array

I'm receiving json data that is aggregated by numerical indexes. When I'm in my forloop, for example, the index might start at 1, which means in my forloop an error would occur bec

Solution 1:

var a = [1, 2, 3], index = 2;

if ( a[index] !== void0 ) { /* void 0 === undefined *//* See concern about ``undefined'' below.        *//* index doesn't point to an undefined item.     */
}

Solution 2:

You should be able to use for(key in data)

vardata = [];
data[1] = 'a';
data[3] = 'b';

for(var index indata) {
  console.log(index+":"+data[index]);
}
//Output:// 1-a// 3-b

Which will loop over each key item in data if the indexes aren't contiguous.

Solution 3:

If what you are actually describing is an Object rather than an Array, but is array like in the fact that it has properties that are of uint32_t but does not have essential length property present. Then you could convert it to a real array like this. Browser compatibility wise this requires support of hasOwnProperty

Javascript

functiontoArray(arrayLike) {
    vararray = [],
        i;

    for (i in arrayLike) {
        if (Object.prototype.hasOwnProperty.call(arrayLike, i) && i >= 0 && i <= 4294967295 && parseInt(i) === +i) {
            array[i] = arrayLike[i];
        }
    }

    returnarray;
}

varobject = {
    1: "a",
    30: "b",
    50: "c",
},
array = toArray(object);

console.log(array);

Output

[1: "a", 30: "b", 50: "c"]`

On jsfiddle

Ok, now you have a sparsely populated array and want to use a for loop to do something.

Javascript

vararray = [],
    length,
    i;

array[1] = "a";
array[30] = "b";
array[50] = "c";

length = array.length;
for (i = 0; i < length; i += 1) {
    if (Object.prototype.hasOwnProperty.call(array, i)) {
        console.log(i, array[i]);
    }
}

Ouput

1 "a"
30 "b"
50 "c"

On jsfiddle

Alternatively, you can use Array.prototype.forEach if your browser supports it, or the available shim as given on the MDN page that I linked, or es5_shim

Javascript

vararray = [];

array[1] = "a";
array[30] = "b";
array[50] = "c";

array.forEach(function (element, index) {
    console.log(index, element);
});

Output

1 "a"
30 "b"
50 "c"

On jsfiddle

Post a Comment for "Checking For A Numerical Index In A Javascript Array"