mirror of
https://github.com/freeCodeCamp/freeCodeCamp.git
synced 2026-06-28 21:00:56 +08:00
feat(curriculum): Add interactive examples to How Do You Get the Index for an Element in an Array Using the indexOf Method (#63290)
Co-authored-by: Ilenia <26656284+ilenia-magoni@users.noreply.github.com>
This commit is contained in:
parent
6a9f66c64a
commit
4e3de7f781
@ -5,7 +5,7 @@ challengeType: 19
|
||||
dashedName: how-do-you-get-the-index-for-an-element-in-an-array-using-the-indexof-method
|
||||
---
|
||||
|
||||
# --description--
|
||||
# --interactive--
|
||||
|
||||
In JavaScript, the `indexOf()` method is useful for finding the first index of a specific element within an array. If the element cannot be found, then it will return `-1`. Here is the basic syntax:
|
||||
|
||||
@ -15,32 +15,44 @@ array.indexOf(element, fromIndex)
|
||||
|
||||
`element` represents the value you want to search for within the array, and the `fromIndex` parameter is the position from which the search should start. The `fromIndex` parameter is optional. If `fromIndex` is not provided, the search starts from the beginning of the array. Let's look at an example:
|
||||
|
||||
:::interactive_editor
|
||||
|
||||
```js
|
||||
let fruits = ["apple", "banana", "orange", "banana"];
|
||||
let index = fruits.indexOf("banana");
|
||||
console.log(index); // 1
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
In this example, we have an array `fruits` containing various fruit names. We use the `indexOf()` method to find the index of the string `banana` within the `fruits` array. Since `banana` is present at index `1`, the method returns `1`, which is stored in the `index` variable and logged to the console.
|
||||
|
||||
If the element you're searching for is not found in the array, `indexOf()` returns `-1`. For example:
|
||||
|
||||
:::interactive_editor
|
||||
|
||||
```js
|
||||
let fruits = ["apple", "banana", "orange"];
|
||||
let index = fruits.indexOf("grape");
|
||||
console.log(index); // -1
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
Here, we search for the string `grape` in the fruits array using `indexOf()`. Since `grape` is not present in the array, the method returns `-1`, which is stored in the `index` variable and logged to the console.
|
||||
|
||||
If you want to start looking for an item after a specific index number, then you can pass a second argument like in this example:
|
||||
|
||||
:::interactive_editor
|
||||
|
||||
```js
|
||||
let colors = ["red", "green", "blue", "yellow", "green"];
|
||||
let index = colors.indexOf("green", 3);
|
||||
console.log(index); // 4
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
In this example, the search does not start from the start of an array, rather it starts from the index number `3` which is `yellow` and gets the output of `4`.
|
||||
|
||||
# --questions--
|
||||
|
||||
Loading…
Reference in New Issue
Block a user