KnockoutJS - slice() Method


Advertisements

Description

The KnockoutJS Observable slice() method slices out a piece of an array. Slice here is the same as native JavaScript slice function. Returns the elements from start-index up to endindex.

Syntax

arrayName.slice(start-index,end-index)

Parameters

Accepts 2 parameters, start-index and end-index.

Example

<!DOCTYPE html>
   <head>
      <title>KnockoutJS ObservableArray slice 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 slice() method.</p>
      
      <p>slice(1,3) to show items starting from index 1 up to 3:
         <span data-bind = "text: empArray().slice(1,3)"></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-slice.htm file.

  • Open this HTML file in a browser.

knockoutjs_observables.htm
Advertisements