目录

splice(start-index,end-index)

描述 (Description)

KnockoutJS Observable splice()方法采用2个参数来指定startindex和end-index。 它从开始到结束索引中删除项目并将它们作为数组返回。

语法 (Syntax)

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

参数 (Parameters)

接受2个参数,start-index是起始索引,end-index是end index。

例子 (Example)

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

输出 (Output)

让我们执行以下步骤来查看上述代码的工作原理 -

  • 将以上代码保存在array-splice.htm文件中。

  • 在浏览器中打开此HTML文件。

  • 单击Splice Emp按钮,观察从索引1到3开始的项目被删除。

新页面打开
↑回到顶部↑
WIKI教程 @2018