KnockoutJS - indexOf() Method


Advertisements

Description

The KnockoutJS Observable indexOf('value') method returns the index of the first occurrence of the parameter provided. This function will return -1, if no matching element is found.

Syntax

arrayName.indexOf('value')

Parameters

Accepts 1 parameter, whose index will be returned.

Example

<!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>

Output

Let's carry out the following steps to see how the above code works −

  • Save the above code in array-indexof.htm file.

  • Open this HTML file in a browser.

knockoutjs_observables.htm
Advertisements