KnockoutJS - reverse() 方法

描述

KnockoutJS Observable reverse() 方法反转数组的顺序。

语法

arrayName.reverse()

参数

不接受任何参数。

示例

<!DOCTYPE html>
   <head>
      <title>KnockoutJS ObservableArray reverse 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 reverse() method.</p>
      <button data-bind = "click: revEmp">Reverse Array</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.revEmp = function() {
               this.empArray.reverse();  // reverse order
            }
         }
         
         var em = new EmployeeModel();
         ko.applyBindings(em);
      </script>
      
   </body>
</html>

输出

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

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

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

  • 单击"反转数组"按钮,观察数组顺序是否发生变化。

knockoutjs_observables.html