KnockoutJS - méthode indexOf ()

La description

L'observable KnockoutJS indexOf('value')La méthode renvoie l'index de la première occurrence du paramètre fourni. Cette fonction retournera -1, si aucun élément correspondant n'est trouvé.

Syntaxe

arrayName.indexOf('value')

Paramètres

Accepte 1 paramètre, dont l'index sera renvoyé.

Exemple

<!DOCTYPE html>
   <head>
      <title>KnockoutJS ObservableArray indexOf method</title>
      <script src = "https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"
         type = "text/javascript"></script>
   </head>

   <body>
      <p>Example to demonstrate indexOf() method.</p>
      
      <p>Index of Employee 'Jordan':
         <span data-bind = "text: empArray().indexOf('Jordan')"></span>
      </p>
      
      <p>Array of employees: <span data-bind = "text: empArray()" ></span></p>

      <script>
         function EmployeeModel() {
            this.empName = ko.observable("");
            this.chosenItem = ko.observableArray("");
            this.empArray = ko.observableArray(['Scott','James','Jordan','Lee',
               'RoseMary','Kathie']);
         }
         
         var em = new EmployeeModel();
         ko.applyBindings(em);
      </script>
      
   </body>
</html>

Production

Exécutons les étapes suivantes pour voir comment fonctionne le code ci-dessus -

  • Enregistrez le code ci-dessus dans array-indexof.htm fichier.

  • Ouvrez ce fichier HTML dans un navigateur.