KnockoutJS - método slice ()

Descripción

El KnockoutJS Observable slice()El método corta una parte de una matriz. Slice aquí es lo mismo que la función de segmento nativo de JavaScript. Devuelve los elementos desde el índice inicial hasta el índice final.

Sintaxis

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

Parámetros

Acepta 2 parámetros, índice inicial y índice final.

Ejemplo

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

Salida

Realicemos los siguientes pasos para ver cómo funciona el código anterior:

  • Guarde el código anterior en array-slice.htm archivo.

  • Abra este archivo HTML en un navegador.