22

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 because 0 doesnt exist.

How do I check if a numerical index exists in the javascript array?

7
  • Lets see an example of this json data Commented Jun 21, 2013 at 22:48
  • 1
    How could an index not exist in an array? What you mean is it's value is undefined, right? Commented Jun 21, 2013 at 22:49
  • 1
    Please post an example. Descriptions of problems in questions are often difficult to answer without concrete examples. Commented Jun 21, 2013 at 22:51
  • You haven't posted any code for us to see why you would have an error, but as a suggestion, have you considered using Array.prototyp.forEach? This will most likely solve your problem (unless Array.length is broken) without you showing us any code. :/ Commented Jun 21, 2013 at 23:31
  • This is a valid question. Arrays in JavaScript can be sparse. They're basically Objects with some special properties. Commented Sep 29, 2014 at 15:28

3 Answers 3

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

if ( a[index] !== void 0 ) { /* void 0 === undefined */
    /* See concern about ``undefined'' below.        */
    /* index doesn't point to an undefined item.     */
}
Sign up to request clarification or add additional context in comments.

8 Comments

Or if (index in a) would technically check for existence, though your !== undefined check will most likely suffice.
typeof a[index] !== 'undefined' should be more safe
@Aubin Why? If a is not defined it will fail just as badly when trying to access [index].
@SammieFox if a developer creates a function with undefined as its parameter name, he's worthy of being skinned alive regardless of programming language used, and worthy of being boiled in tar afterwards if he's coding in JS. FWIW, I wouldn't go with void 0 instead of undefined just for that reason - it's not "defensive coding", it's "paranoid coding" since ES5. void 0 is semantic noise, undefined is semantically correct. We should program with humans in mind, not computers, IMVHO.
@vaxquis Setting undefined as an (undefined) parameter-value, was a recommend coding-style for IIFE-patterns, to make sure that the undefined-parameter is really undefined and not already defined outside the scope (e.g. by third-party-scripts). But yeah, its unneccassary since ES5 with strict mode. books.google.de/… ---- toddmotto.com/…
|
6

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

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

for(var index in data) {
  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.

Comments

0

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

function toArray(arrayLike) {
    var array = [],
        i;

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

    return array;
}

var object = {
    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

var array = [],
    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

var array = [];

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.