随机化测验顺序问题

时间:2015-08-27 16:10:48

标签: arrays json angularjs sorting ionic-framework

我有一个测验,想要随机化来自我的jSON文件的数据,这样每次有人尝试测验都会看到不同的问题顺序。

我遇到了this example,但无法通过我的jSON文件中的数组来解决问题。见下面的JS:

.controller('QuizController', ['$scope', '$http', function($scope, $http, $state){
  $scope.score = 0;
  $scope.activeQuestion = -1;
  $scope.activeQuestionAnswered = 0;
  $scope.percentage= 0;

  $http.get('js/quiz_data.json').then(function(quizData){
    $scope.myQuestions = quizData.data;
    $scope.totalQuestions = $scope.myQuestions.length;
  });

  $scope.randomSort = function(myQuestion) {
    return Math.random();
  };

HTML:

ng-repeat="myQuestion in myQuestions|orderBy:randomSort">

如果答案也是随机顺序,那就太好了...... 提前谢谢!

1 个答案:

答案 0 :(得分:1)

这可能会有所帮助 How to randomize (shuffle) a JavaScript array?

您可以在JSON对象上使用相同的概念

修改

 function createobj() {
        var obj = [
            {"Question":"This is the first question","Answer":"This is the first Answer"},
            {"Question":"This is the second question","Answer":"This is the second Answer"},
            {"Question":"This is the third question","Answer":"This is the third Answer"},
            {"Question":"This is the forth question","Answer":"This is the forth Answer"},
            {"Question":"This is the fifth question","Answer":"This is the fifth Answer"},
        ];
    //Assigning the obj to the new one
        obj = randomize(obj);
    }

    function randomize (obj) {
        var index;
        var temp;
        for (var i = obj.length - 1; i > 0; i--) {
            //get random number
            index = Math.floor((Math.random() * i));
            //swapping
            temp = obj[index];
            obj[index] = obj[i];
            obj[i] = temp;
        }
        //Prints the results into the console
        for (i = 0; i < obj.length; i++) {
            console.log(obj[i].Question + ": " + obj[i].Answer);
        }
//My edit to pass the obj back to the function
        return obj;

    }

Here is the function, it takes a simple JSON object i created and randomizes it. It will print the results into the Console. Hope this helps more.