JavaScript-如何基于索引调用不同的函数,同时通过AngularJ中的数组循环



我想创建一个JavaScript数组的循环,当数组0的索引0时,将执行范围函数f0。同样,当索引为F1时,将执行范围函数F1。在此中,它将继续用于阵列的所有索引。对于每个索引(循环(,将执行一个特定的功能。

var myArray = ["0","1","2","3","4","5"];
var len = myArray.length;
for(var i = 0; i < len; i++)
{
if(index is 0){function0() code}
if(index is 1){function1() code}
................
}

函数将是角范围函数,例如$ scope.f1 = function(({}

angular.module('app', [])
.controller('myController', function ($scope) {
  
  $scope.f0 = function () {console.log('func f0 has been called')};
  $scope.f1 = function () {console.log('func f1 has been called')};
  
  var myArray = ["0","1"];
  // using angular foreach
  angular.forEach(myArray, function (item, index) {
    $scope['f' + index]();
  });
  // using native foreach
  myArray.forEach(function (item, index) {
    $scope['f' + index]();
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="app">
  <div ng-controller="myController"></div>
</body>

最新更新