For instance, a variable named arrayElements of array type contains [1,2,3,4].
How do i get the position of which that has the value "3" in the array variable besides using loop?
thanks.
Definition and Usage. The indexOf() method returns the first index (position) of a specified value. The indexOf() method returns -1 if the value is not found. The indexOf() method starts at a specified index and searches from left to right. By default the search starts at the first element and ends at the last.
lastIndexOf() The lastIndexOf() method returns the last index at which a given element can be found in the array, or -1 if it is not present. The array is searched backwards, starting at fromIndex .
findIndex - Returns the index of the first element in the array where predicate is true, and -1 otherwise. indexOf - Returns the index of the first occurrence of a value in an array.
consider using indexOf
, it returns the 0-based position of the element in the array.
e.g.
[1,2,3,4].indexOf(3); // produces 2
Note that this method is not available in IE 8 and below.
jQuery provides yout with an "inArray" functionality, similar to PHP:
var a = [1,2,3,4]; console.log( jQuery.inArray(3, a) ); //returns 2
If you're already using jQuery in your project, this would be the way to go! jQuery uses indexOf (the fastest solution) if possible and steps back to a loop based solution if not.
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