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

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

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

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

Синтаксис:

_.lastIndexOf(array, value, [fromIndex])

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

  • Массив
  • Значение
  • Индекс, с которого нужно начать поиск (необязательно)

Возвращаемое значение:
Он возвращает индекс повторяющегося элемента, который находится ближе всего к концу массива.

Примеры:

  1. Passing a list of characters to the _.lastIndexOf() function:
    The _.lastIndexOf() function takes the element from the list one by one starting from the end of the array and checks whether that element matches with the second parameter passed or not. If it matches, then the index of that element is returned otherwise that element is ignored and the element preceding it is checked in the passed array.




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

    Output:

  2. Passing a value which is not present in the array:
    If we pass an element as the second parameter which is not present in the array then the _.lastIndexOf() function will work in the same manner. the search will start in the same manner for that element. It will keep on ignoring the present element and go onto the preceding element till the list ends. Once the array is exhausted then this function will return a negative value, -1 indicating that the element passed is not present in the array.




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

    Output:

  3. Passing a list of numbers to _.lastIndexOf() function:
    The _.lastIndexOf() function takes the element from the list one by one and works the same way as it does for characters in example 1. This function does not distinguish between a number or a character or string of characters. Therefore, the search will go on smoothly and the result will be displayed.




    <!-- Write HTML code here -->
    <html>
       
    <head>
        <script src
        </script>
    </head>
       
    <body>
        <script type="text/javascript">
            console.log(_.lastIndexOf([1, 2, 3, 4, 5, 6], 4));
        </script>
    </body>
       
    </html>

    Output:

  4. Passing a heterogeneous array to the _.lastIndexOf() function:
    Like we can pass a number array, a character array etc in the same way we can also pass a heterogeneous array. A heterogeneous array contains the combination of numbers, strings or characters. The _.lastIndexOf() function will also not give any error in this case. Rather will give the expected output.




    <!-- Write HTML code here -->
    <html>
       
    <head>
        <script src
        </script>
    </head>
       
    <body>
        <script type="text/javascript">
            console.log(_.lastIndexOf(["HTML", 1, "CSS", "JS", 2,
                     "AJAX", "PEARL", "CSS", 3, "HTML", "CSS"], 3));
        </script>
    </body>
       
    </html>

    Output:

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

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