KnockoutJS - méthode splice ()

La description

L'observable KnockoutJS splice()La méthode prend 2 paramètres spécifiant le startindex et le end-index. Il supprime les éléments de l'index de début à la fin et les renvoie sous forme de tableau.

Syntaxe

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

Paramètres

Accepte 2 paramètres, start-index est l'index de début et end-index est l'index de fin.

Exemple

<!DOCTYPE html>
   <head>
      <title>KnockoutJS ObservableArray splice 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 splice() method.</p>
      <button data-bind = "click: spliceEmp">Splice Emp</button>
      <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']);

            this.spliceEmp = function() {
               alert("Splice is removing items from index 1 to 3(If exists).");
               this.empArray.splice(1,3);   // remove 2nd,3rd and 4th item, as array index 
                                            //starts with 0.
            }
         }

         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-splice.htm fichier.

  • Ouvrez ce fichier HTML dans un navigateur.

  • Cliquez sur le bouton Splice Emp et observez que les éléments commençant par les index 1 à 3 sont supprimés.