Функция Underscore.js _.indexOf()

Опубликовано: 7 Октября, 2022

Функция _.indexOf():

  • Он дает индекс элементов, положение которых нам нужно найти.
  • Он начинает считать позиции элементов в массиве, начиная с 0.
  • Если элемент отсутствует в массиве, результатом будет -1.

Синтаксис:

_.indexOf(array, value, [isSorted])

Параметры:
Он принимает три аргумента:

  • Массив
  • Значение
  • isSorted (необязательно)

Возвращаемое значение:
Возвращает позицию переданного элемента.

Примеры:

  1. Passing a list of numbers to _.indexOf() function:
    The ._indexOf() function takes the element from the list one by one and checks whether it is equal to the passed element in the second parameter. If it is equal then the result is it’s index otherwise -1 is returned.




    <html>
       
    <head>
        <script src
        </script>
    </head>
       
    <body>
        <script type="text/javascript">
            console.log(_.indexOf([1, 2, 3, 4, 5, 6], 4));
        </script>
    </body>
       
    </html>

    Output:

  2. Passing a list of characters to the _.indexOf() function:
    We can also pass the list of characters to the _.indexOf() function and it will work in the same way as the numbers list works. In the second parameter we need to mention the word whose index we need to find inside single quotes, ”.




    <html>
       
    <head>
        <script src
        </script>
    </head>
       
    <body>
        <script type="text/javascript">
            console.log(_.indexOf(["HTML", "CSS", 
                      "JS", "AJAX", "PEARL"], "AJAX"));
        </script>
    </body>
       
    </html>

    Output:

  3. Passing second parameter which is not present in the list::
    Pass the list of character elements to the _.indexOf() function. SIince in the given list the second parameter ‘GEEKS’ is not present so the result will be -1.




    <html>
       
    <head>
        <script src
        </script>
    </head>
       
    <body>
        <script type="text/javascript">
            console.log(_.indexOf(["HTML", "CSS", "JS",
                      "AJAX", "PEARL"], "GEEKS"));
        </script>
    </body>
       
    </html>

    Output:

  4. Passing a list with repeated elements to the _.indexOf() function: Even tough we pass an array with the repeated element the _.indexOf() function will work in the same way and return the index where the element passed in the second parameter is found first.




    <html>
       
    <head>
        <script src
        </script>
    </head>
       
    <body>
        <script type="text/javascript">
            console.log(_.indexOf(["HTML", "CSS", "JS", "AJAX",
                         "PEARL", "CSS", "HTML", "CSS"], "CSS"));
        </script>
    </body>
       
    </html>

    Output:

ПРИМЕЧАНИЕ:
Эти команды не будут работать в консоли Google или в Firefox, поскольку необходимо добавить эти дополнительные файлы, которых они не добавили.
Итак, добавьте указанные ссылки в свой HTML-файл, а затем запустите их.
Ссылки следующие:

Пример показан ниже: