Angularjs如何实现数组随机排序的方法

Angularjs如何实现数组随机排序的方法

小编给大家分享一下Angularjs如何实现数组随机排序的方法,希望大家阅读完这篇文章之后都有所收获,下面让我们一起去探讨吧!

JS是什么

JS是JavaScript的简称,它是一种直译式的脚本语言,其解释器被称为JavaScript引擎,是浏览器的一部分,主要用于web的开发,可以给网站添加各种各样的动态效果,让网页更加美观。

如下所示:

<!DOCTYPE html>
<html>
 <head>
  <meta charset="UTF-8">
  <title>实现数组随机排序</title>
  //需要导入angular.js库文件
  <script type="text/javascript" src="../angular-1.5.5/angular-1.5.5/angular.js"></script>
  <script type="text/javascript">
   var app = angular.module("myApp", []);
   var arr1 = [1, 2, 3, 7, 4, 9, 5, 6];
   app.service("sortService", function() {
    this.arr = [1, 2, 3, 7, 4, 9, 5, 6];
    this.t;
    this.mySort = function() {
     //alert("haha");
     for(var i = 0; i < this.arr.length; i++) {
      var rand = parseInt(Math.random() * this.arr.length);
      this.t = this.arr[rand];
      this.arr[rand] = this.arr[i];
      this.arr[i] = this.t;
     }
    }
   })
   app.controller("myCtrl", function($scope, sortService) {
    $scope.arr = arr1;
    $scope.newArr = sortService.arr;
    $scope.mySort2 = sortService.mySort;
    
    /*$scope.mySort2 = function(){
     sortService.mySort();
    }*/
   })
  </script>
 </head>
 <body ng-app="myApp" ng-controller="myCtrl">
  {{newArr}}<br><button ng-click="mySort2()">点击随机排序</button> <br>{{arr}}
  <!--{{arr}}<button ng-click="mySort2()">点击随机排序</button> {{newArr}}-->
 </body>
</html>

Angularjs如何实现数组随机排序的方法

看完了这篇文章,相信你对“Angularjs如何实现数组随机排序的方法”有了一定的了解,如果想了解更多相关知识,欢迎关注行业资讯频道,感谢各位的阅读!