dexOf() - JavaScript - MDN - Mozilla
Có thể bạn quan tâm
- Skip to main content
- Skip to search
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
- Learn more
- See full compatibility
- Report feedback
The indexOf() method of Array instances returns the first index at which a given element can be found in the array, or -1 if it is not present.
In this article
- Try it
- Syntax
- Description
- Examples
- Specifications
- Browser compatibility
- See also
Try it
const beasts = ["ant", "bison", "camel", "duck", "bison"]; console.log(beasts.indexOf("bison")); // Expected output: 1 // Start from index 2 console.log(beasts.indexOf("bison", 2)); // Expected output: 4 console.log(beasts.indexOf("giraffe")); // Expected output: -1Syntax
jsindexOf(searchElement) indexOf(searchElement, fromIndex)Parameters
searchElementElement to locate in the array.
fromIndex OptionalZero-based index at which to start searching, converted to an integer.
- Negative index counts back from the end of the array — if -array.length <= fromIndex < 0, fromIndex + array.length is used. Note, the array is still searched from front to back in this case.
- If fromIndex < -array.length or fromIndex is omitted, 0 is used, causing the entire array to be searched.
- If fromIndex >= array.length, the array is not searched and -1 is returned.
Return value
The first index of searchElement in the array; -1 if not found.
Description
The indexOf() method compares searchElement to elements of the array using strict equality (the same algorithm used by the === operator). NaN values are never compared as equal, so indexOf() always returns -1 when searchElement is NaN.
The indexOf() method skips empty slots in sparse arrays.
The indexOf() method is generic. It only expects the this value to have a length property and integer-keyed properties.
Examples
Using indexOf()
The following example uses indexOf() to locate values in an array.
jsconst array = [2, 9, 9]; array.indexOf(2); // 0 array.indexOf(7); // -1 array.indexOf(9, 2); // 2 array.indexOf(2, -1); // -1 array.indexOf(2, -3); // 0You cannot use indexOf() to search for NaN.
jsconst array = [NaN]; array.indexOf(NaN); // -1Finding all the occurrences of an element
jsconst indices = []; const array = ["a", "b", "a", "c", "a", "d"]; const element = "a"; let idx = array.indexOf(element); while (idx !== -1) { indices.push(idx); idx = array.indexOf(element, idx + 1); } console.log(indices); // [0, 2, 4]Finding if an element exists in the array or not and updating the array
jsfunction updateVegetablesCollection(veggies, veggie) { if (veggies.indexOf(veggie) === -1) { veggies.push(veggie); console.log(`New veggies collection is: ${veggies}`); } else { console.log(`${veggie} already exists in the veggies collection.`); } } const veggies = ["potato", "tomato", "chillies", "green-pepper"]; updateVegetablesCollection(veggies, "spinach"); // New veggies collection is: potato,tomato,chillies,green-pepper,spinach updateVegetablesCollection(veggies, "spinach"); // spinach already exists in the veggies collection.Using indexOf() on sparse arrays
You cannot use indexOf() to search for empty slots in sparse arrays.
jsconsole.log([1, , 3].indexOf(undefined)); // -1Calling indexOf() on non-array objects
The indexOf() method reads the length property of this and then accesses each property whose key is a nonnegative integer less than length.
jsconst arrayLike = { length: 3, 0: 2, 1: 3, 2: 4, 3: 5, // ignored by indexOf() since length is 3 }; console.log(Array.prototype.indexOf.call(arrayLike, 2)); // 0 console.log(Array.prototype.indexOf.call(arrayLike, 5)); // -1Specifications
| Specification |
|---|
| ECMAScript® 2026 Language Specification# sec-array.prototype.indexof |
Browser compatibility
See also
- Polyfill of Array.prototype.indexOf in core-js
- es-shims polyfill of Array.prototype.indexOf
- Indexed collections guide
- Array
- Array.prototype.findIndex()
- Array.prototype.findLastIndex()
- Array.prototype.lastIndexOf()
- TypedArray.prototype.indexOf()
- String.prototype.indexOf()
Help improve MDN
Was this page helpful to you? Yes No Learn how to contributeThis page was last modified on Jul 10, 2025 by MDN contributors.
View this page on GitHub • Report a problem with this content Filter sidebar- Standard built-in objects
- Array
- Constructor
- Array()
- Static methods
- from()
- fromAsync()
- isArray()
- of()
- Static properties
- [Symbol.species]
- Instance methods
- at()
- concat()
- copyWithin()
- entries()
- every()
- fill()
- filter()
- find()
- findIndex()
- findLast()
- findLastIndex()
- flat()
- flatMap()
- forEach()
- includes()
- indexOf()
- join()
- keys()
- lastIndexOf()
- map()
- pop()
- push()
- reduce()
- reduceRight()
- reverse()
- shift()
- slice()
- some()
- sort()
- splice()
- toLocaleString()
- toReversed()
- toSorted()
- toSpliced()
- toString()
- unshift()
- values()
- with()
- [Symbol.iterator]()
- Instance properties
- length
- [Symbol.unscopables]
- Inheritance
- Object/Function
- Static methods
- apply()
- bind()
- call()
- toString()
- [Symbol.hasInstance]()
- Static properties
- displayName Non-standard
- length
- name
- prototype
- arguments Non-standard Deprecated
- caller Non-standard Deprecated
- Instance methods
- __defineGetter__() Deprecated
- __defineSetter__() Deprecated
- __lookupGetter__() Deprecated
- __lookupSetter__() Deprecated
- hasOwnProperty()
- isPrototypeOf()
- propertyIsEnumerable()
- toLocaleString()
- toString()
- valueOf()
- Instance properties
- __proto__ Deprecated
- constructor
Từ khóa » Hàm Indexof
-
Hàm dexOf() Trong Javascript - Freetuts
-
Hàm IndexOf() Trong JavaScript | Học Lập Trình JavaScript
-
String IndexOf() Trong JavaScript - Hoclaptrinh
-
IndexOf() Trong JavaScript | Tìm Vị Trí Xuất Hiện đầu Tiên Của Một ...
-
Thao Tác Với IndexOf Trong Java - NIIT - ICT Hà Nội
-
JavaScript String IndexOf() Method - W3Schools
-
JavaScript Array IndexOf() Method - W3Schools
-
Hàm INDEX - Microsoft Support
-
Phương Thức IndexOf Trong Java String - Học Java Miễn Phí Hay Nhất
-
IndexOf() Function | Help - Zoho Deluge
-
Indexof Function - Millisecond
-
INDEX Function - SAS Help Center
-
INDEX Function - SAS Help Center