KnockoutJS - splice() 方法
描述
KnockoutJS Observable splice() 方法采用 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.htm 文件中。
在浏览器中打开此 HTML 文件。
单击 Splice Emp 按钮并观察从索引 1 到 3 开始的项目被删除。

knockoutjs_observables.html