简体   繁体   English

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

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

I have have been working with AngularJS. 我一直在使用AngularJS。 I have a JSON file of which each object needs to be displayed in a new partial. 我有一个JSON文件,每个对象都需要显示在新的部分中。 There are 100 objects in the JSON file, I need to randomly choose three. JSON文件中有100个对象,我需要随机选择三个。 How do I achieve this? 我该如何实现?

the controller: 控制器:

 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;
  }

  });
}]);

Currently it is taking in all 100 items... 目前它正在吸收所有100个物品...

To access a random item in your array you can use. 要访问数组中的随机项,可以使用。

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

If you repeat it three times then you get the three random elements. 如果重复三遍,则会得到三个随机元素。 Still you could create a function to make the code DRY. 您仍然可以创建一个函数来使代码干燥。

function getRandomItem(items) {

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

The solution above could get the same item multiple times if it is called three times. 如果多次调用同一项,则上述解决方案可能会多次获得相同的项。 You could use splice() to remove the item from the original array. 您可以使用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