KnockoutJS - shift() 方法



說明

KnockoutJS 可觀察 shift() 方法從陣列中移除第一個元素並返回它。

語法

arrayName.shift()

引數

不接受任何引數。

示例

<!DOCTYPE html>
   <head>
      <title>KnockoutJS ObservableArray shift 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 shift() method.</p>
      <button data-bind = "click: shiftEmp">Remove First 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.shiftEmp = function() {
               this.empArray.shift();     //remove first item
            }
         }
         
         var em = new EmployeeModel();
         ko.applyBindings(em);
      </script>
      
   </body>
</html>

輸出

讓我們執行以下步驟來了解以上程式碼如何執行 -

  • 將以上程式碼另存為 array-shift.htm 檔案。

  • 在瀏覽器中開啟此 HTML 檔案。

  • 單擊“移除第一個員工”按鈕,觀察第一個元素被移除。

《knockoutjs_observables.htm》
廣告
© . All rights reserved.