【问题标题】:Randomize quiz order questions随机化测验顺序问题
【发布时间】:2015-11-22 03:23:23
【问题描述】:

我有一个测验,想随机化来自我的 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">

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

【问题讨论】:

  • 你能提供一个 JSON 的例子吗?
  • 是的,就是这样:{ "question" : "Qual o número total de biomas no Brasil?", "answers" : [ {"id" : 0, "text" : "27" },{“id”:1,“text”:“5”},{“id”:2,“text”:“6”},{“id”:3,“text”:“26”}] , "正确" : 2 },
  • 从已经随机排序的GET返回结果是否可行?喜欢将逻辑推到后端?

标签: arrays json angularjs sorting ionic-framework


【解决方案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.

【讨论】:

  • 您好,感谢您的回答。我真的不知道如何用你的小费解决我的问题。即使有一个更接近上下文的例子,我也无法解决这个问题。看看:jsfiddle.net/q6kv7
  • 编辑我的答案,我为你做了一个简单的随机化器。
  • 谢谢,杰森!请原谅我缺乏 js 知识,但是,在您的回答中,您直接在函数上传递了 json,我应该如何将 json“链接”到变量?
  • IDK jason 是谁,但是链接是什么意思?如果您的意思是将随机的 json obj 返回给函数,请编辑我的答案以向您展示我认为您想要的内容。
  • 对不起,杰克!当我说“链接”时,我的意思是我的源 JSON 文件:'js/quiz_data.json'。谢谢!!!
猜你喜欢
  • 1970-01-01
  • 2017-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多