Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 351
somejkuser Avatar asked Jun 21 '13 22:06

somejkuser


People also ask

How to find the index of an array in JavaScript?

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.

How to find the index of an even number in JavaScript?

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).

How to search for negative values in an array in JavaScript?

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:

What does array findindex () return?

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:


Video Answer


2 Answers

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.     */ } 
like image 67
Andreas Louv Avatar answered Sep 30 '22 18:09

Andreas Louv


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.

like image 26
JasonM Avatar answered Sep 30 '22 18:09

JasonM