Javascript测验 - 使用Array.prototype以随机顺序显示选项 [英] Javascript quiz - display choices in a random order using Array.prototype

查看:72
本文介绍了Javascript测验 - 使用Array.prototype以随机顺序显示选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想随机化选择的顺序。我添加了一个脚本,该脚本应该改变选择的顺序,但它没有这样做。调试测验时没有显示任何内容。

I want to randomize the order of the choices. I added a script that was supposed to shuffle the order of the choices but it failed to do so. Nothing displays when I debug the quiz.

这是我添加的代码:

function shuffle(array) {
  var currentIndex = array.length, temporaryValue, randomIndex;

  // While there remain elements to shuffle...
  while (0 !== currentIndex) {

    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    // And swap it with the current element.
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;
}

Javascript测验:

Javascript Quiz:

 var quiz = [{
          "question": "What is the full form of IP?",
          "choices": ["Internet Provider", "Internet Port", "Internet Protocol" , "Other"],
          "correct": "Other"

        }, {
          "question": "Who is the founder of Microsoft?",
          "choices": ["Bill Gates", "Steve Jobs", "Steve Wozniak" , "Martin Shaba"],
          "correct": "Bill Gates"
        }, {
          "question": "What was your first dream?",
          "choices": ["8 bits", "64 bits", "1024 bits"],
          "correct": "8 bits"
        }, {
          "question": "The C programming language was developed by?",
          "choices": ["Brendan Eich", "Dennis Ritchie", "Guido van Rossum"],
          "correct": "Dennis Ritchie"
        }, {
          "question": "What does CC mean in emails?",
          "choices": ["Carbon Copy", "Creative Commons", "other"],
          "correct": "Carbon Copy"
        }];


推荐答案

添加争夺函数到 Array.prototype

if (!("scramble" in Array.prototype)) {
  Object.defineProperty(Array.prototype, "scramble", {
    enumerable: false,
    value: function() {
      var o, i, ln = this.length;
      while (ln--) {
        i = Math.random() * (ln + 1) | 0;
        o = this[ln];
        this[ln] = this[i];
        this[i] = o;
      }
      return this;
    }
  });
}
var quiz = [{
  "question": "What is the full form of IP?",
  "choices": ["Internet Provider", "Internet Port", "Internet Protocol", "Other"],
  "correct": "Other"
}];

quiz.forEach(q => q.choices.scramble());

console.log(quiz[0].choices);

最初我曾建议:

quiz.forEach(q => q.choices.sort(() => Math.random() - .5));

DanDavis 指出特定方法没有达到合理的分配。

DanDavis pointed out that particular method didn't achieve a reasonable distribution.

这篇关于Javascript测验 - 使用Array.prototype以随机顺序显示选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆