Checking for a numerical index in a javascript array [closed] Checking for a numerical index in a javascript array [closed] arrays arrays

Checking for a numerical index in a javascript array [closed]


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.     */}


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.


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