Knockoutjs-obs-array-splice

提供:Dev Guides
移動先:案内検索

KnockoutJS-splice()メソッド

説明

KnockoutJS Observable * splice()*メソッドは、startindexとend-indexを指定する2つのパラメーターを取ります。 開始インデックスから終了インデックスまでのアイテムを削除し、配列として返します。

構文

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

パラメーター

2つのパラメーターを受け入れます。start-indexは開始インデックスで、end-indexは終了インデックスです。

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

出力

上記のコードがどのように機能するかを確認するために、次の手順を実行してみましょう-

  • 上記のコードを array-splice ファイルに保存します。
  • このHTMLファイルをブラウザーで開きます。
  • Splice Empボタンをクリックして、インデックス1から3までのアイテムが削除されることを確認します。