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?
The JavaScript Array findIndex () method returns the index of the first array element that satisfies the provided test function or else returns -1. The syntax of the findIndex () method is: arr.findIndex (callback (element, index, arr),thisArg) Here, arr is an array.
In the above example, we have used the findIndex () method to find the index of the first even number in the numbers array. isEven () is a function that returns an even number. We have passed isEven () as a callback in the findIndex () method as- numbers.findIndex (isEven).
Negative values start the search from the end of the array. The index (position) of the first item found. -1 if the item is not found. In an array, the first element has index (position) 0, the second has index 1, ... indexOf () is an ES5 feature (JavaScript 2009). It is fully supported in all modern browsers:
The Array.findIndex () method returns the index of the first array element that passes a test (provided by a function). Array.findIndex () does not execute the function for empty array elements. Array.findIndex () does not change the original array. The numbers in the table specify the first browser version that fully supports the method:
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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With