Функция Underscore.js _.sample

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

Underscore.js — это библиотека JavaScript, которая предоставляет множество полезных функций, которые сильно помогают в программировании, таких как отображение, фильтрация, вызовы и т. д., даже без использования каких-либо встроенных объектов.

Функция _.sample() используется для определения того, какие элементы присутствуют в массиве. Он дает случайный элемент массива в качестве вывода. Мы даже можем передать второй параметр, чтобы вернуть это количество случайных элементов из массива.

Синтаксис:

_.sample(list, [n])

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

  • Список
  • число п

Возвращаемые значения:
Он возвращает элемент из переданного массива.

  • Passing a list of numbers to the _.sample() function:
      The ._sample() function uses a random function and then displays that element from the list as the result. If the second parameter is not mentioned then t’s default value will be taken which is 1. Hence, any one of the element will be displayed.




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

      Output:

    • Passing the second parameter to the _.sample() function:
      Id we pass the second parameter then the _.sample() function will return as many elements from the passed list as mentioned. The result will be an array containing the number of elements which is present in the second parameter.




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

      Output:

    • Passing a structure to the _.sample() function:
      We can even pass a structure to the _.sample() function and it will work in the same manner. It will display any of the element of the structure randomly as the output. Since, no second parameter is mentioned therefore, it will have only one element of the passed list in the result along with it’s all properties.




      <!-- Write HTML code here -->
      <html>
         
      <head>
          <script src
          </script>
      </head>
         
      <body>
          <script type="text/javascript">
               var people = [
              {"name": "sakshi", "hasLong": "false"},
              {"name": "aishwarya", "hasLong": "true"},
              {"name": "akansha", "hasLong": "true"},
              {"name": "preeti", "hasLong": "true"}
          ]
           console.log(_.sample(people));
          </script>
      </body>
         
      </html>

      Output:

    • Passing a structure with only one property to the _.sample() function together:
      If we pass a structure with only one property then it will work in the same way and display any one of the element randomly from the structure passed. Here also, since the second parameter is not mentioned therefore, the resultant array will contain only one element.




      <!-- Write HTML code here -->
      <html>
         
      <head>
          <script src
          </script>
      </head>
         
      <body>
          <script type="text/javascript">
               var users = [{"num":"10"}, {"num":"9"}, 
      {"num":"8"}, {"num":"7"}, {"num":"6"}];
          console.log(_.sample(users));
          </script>
      </body>
         
      </html>

      Output:

    NOTE:
    These commands will not work in Google console or in firefox as for these additional files need to be added which they didn’t have added.
    So, add the given links to your HTML file and then run them.
    The links are as follows:




    <!-- Write HTML code here -->
    <script type="text/javascript" src =
    </script>

    An example is shown below: