【问题标题】:What will be a correct data structure for questionnaire [closed]问卷的正确数据结构是什么[关闭]
【发布时间】:2016-05-23 17:36:12
【问题描述】:

我正在尝试开发一个问题取决于答案的问卷,
什么是正确的 UI 数据结构来保存问题和问卷流程?

抱歉,如果不清楚,想根据答案消除 UI 的某些部分,所以我需要 Java 脚本中的某种数据结构,以便我可以根据答案动态修改 html,所以问题是如何将数据以 json 的形式带到页面中,以及如何将数据保存在 JS 中并根据 json 和答案消除 UI 的某些部分。

1 What is your name?_______
2 Did you ever code in java?___Y/N____
     3 <Question should appear only if answer is yes> How many years? ____
     4 <Question should appear only if answer is no> Did you ever code using any programming language? ____
5 Select occupation 
        a Developer
        b Project manager
6 <Question should appear only if answer to 5 is b> years experience in project management ________

【问题讨论】:

  • 最明显的答案是每个条件问题树的 BST。
  • @Paul:那将是二叉树,而不是二叉搜索树。
  • @JimMischel 对不起,把两者搞混了。我的意思是二叉树
  • 如果我们有更多的问题或更多的先决条件而不是 OP 提供的示例,如果我们不想有相同的问题,则使用图形结构(例如树)来捕获所有先决条件可能不起作用在我们的图表中出现多次。
  • 请不要再更改问题的编程语言。因为如果您再次更改语言,我和 Ie_m 将一无所获。我想这是一种不公平的收集声誉的方法。

标签: javascript jquery json user-interface data-structures


【解决方案1】:

假设我们只有以下约束:

  • 您希望每个问题只定义一次
  • 一个问题可以取决于任何先前提出的问题的任何答案

那么我提出以下通用解决方案:

// Each question has an id, a text and a condition depending on previous answers:
var questions = [
  {id: "name", text: "What is your name?"},
  {id: "code-java", text: "Did you ever code in Java?"},
  {id: "code-java-years", text: "How many years?", condition: answers => answers["code-java"] == "yes"},
  {id: "code-other", text: "Did you ever code using any programming language?", condition: answers => answers["code-java"] == "no"},
  {id: "occupation", text: "Select occupation?"},
  {id: "experience-management-years", text: "Years experience in project management?", condition: answers => answers["occupation"] == "Project manager"}
]

// Ask all questions whose conditions evaluate to true and collect the answers:
var answers = {};
questions.forEach(question => {
  if (!question.condition || question.condition(answers)) {
    answers[question.id] = prompt(question.text);
  }
});

console.log(answers);

您可能希望为每个问题添加更多详细信息,例如验证函数、类型(布尔值、文本、选择...)等。

如果您需要以纯 JSON 格式存储和传输您的问题,则需要将您的条件函数替换为 conditions: [{id: "code-java", operator: "equals", value: "yes"}] 之类的数据结构,该结构由以下机构评估

operators = {
  'equals': (answer, value) => answer == value,
  'regex': (answer, value) => new RegExp(value).test(answer),
  ...
}

conditions.every(condition => operators[condition.operator](answers[condition.id], condition.value))

【讨论】:

    猜你喜欢
    • 2014-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-06
    • 2019-12-25
    • 1970-01-01
    相关资源
    最近更新 更多