繁体   English   中英

AngularJS:从JSON文件中获取三个随机元素

[英]AngularJS: Getting three random elements from a JSON file

我一直在使用AngularJS。 我有一个JSON文件,每个对象都需要显示在新的部分中。 JSON文件中有100个对象,我需要随机选择三个。 我该如何实现?

控制器:

 myApp.controller('DetailsController', ['$scope', '$http','$routeParams' ,function($scope, $http, $routeParams) {
  $http.get('js/JOSCO.json').success(function(data) {
  $scope.questions = data; // Array of 100 objs
  console.log($scope.questions);
  $scope.whichItem = $routeParams.itemId; // I want to assign 3 random numbers to whichItem

 if($routeParams.itemId > 0){
    $scope.prevItem = Number($routeParams.itemId) - 1;
  }
  else{
    $scope.prevItem = $scope.questions.length - 1;
  }

  if($routeParams.itemId < $scope.questions.length-1){
    $scope.nextItem = Number($routeParams.itemId) + 1;
  }
  else{
    $scope.nextItem = 0;
  }

  });
}]);

目前它正在吸收所有100个物品...

要访问数组中的随机项,可以使用。

$scope.randomItem = data[Math.floor(Math.random() * data.length)];

如果重复三遍,则会得到三个随机元素。 您仍然可以创建一个函数来使代码干燥。

function getRandomItem(items) {

  return items[Math.floor(Math.random() * items.length)];
}

如果多次调用同一项,则上述解决方案可能会多次获得相同的项。 您可以使用splice()从原始数组中删除该项。

function getRandomItem(items) {
    var randomIndex = Math.floor(Math.random() * items.length);
    var item = items.splice(randomIndex, 1);
    return item[0];
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM