-
Notifications
You must be signed in to change notification settings - Fork 2
JS Array Prototype IndexOf
The indexOf()
method returns the first index at which a given element can be found in the array, or -1 if it is not present!!
arr.indexOf(searchElement[, fromIndex = 0])
| Parameter
-------- | ------------- Required | Arr Required | searchElement Optional | fromIndex
Return: -1 if the element is not found in the array or an integer >=0, the position of the element in the array
Use Case: Check to see if there are any apples in the fruit basket (defined as an array)?
var basket = ['apple','orange','banana','strawberry'];
Without indexOf()
var found = false;
for(var i= 0, l = basket.length; i< l; i++){
if(basket[i] === 'apple'){
found = true;
break;
}
}
console.log(found);
With indexOf()
console.log(basket.indexOf("apple") != -1);
tags: js, array
Learn to code and help nonprofits. Join our open source community in 15 seconds at http://freecodecamp.com
Follow our Medium blog
Follow Quincy on Quora
Follow us on Twitter
Like us on Facebook
And be sure to click the "Star" button in the upper right of this page.
New to Free Code Camp?
JS Concepts
JS Language Reference
- arguments
- Array.prototype.filter
- Array.prototype.indexOf
- Array.prototype.map
- Array.prototype.pop
- Array.prototype.push
- Array.prototype.shift
- Array.prototype.slice
- Array.prototype.some
- Array.prototype.toString
- Boolean
- for loop
- for..in loop
- for..of loop
- String.prototype.split
- String.prototype.toLowerCase
- String.prototype.toUpperCase
- undefined
Other Links