在构建调查问卷时使用的Javascript数组的正确类型是什么?

时间:2012-11-14 21:13:16

标签: javascript arrays

我正在构建一个单页问卷调查应用程序,我不确定为问题构建数组的正确方法是什么。另外,以这种方式混合问题类型是不好的做法吗? (单选,多选在同一阵列?)基本上,我仍然试图了解我所见过的两种基本方法的优点/缺点。

选项1:

var hygiene = [

  {
    pageheader: "Self-Care"
  }

  {
    q: "When was your last shower?",
    choicetype: "radio",
    a1: "Today",
    a2: "Yesterday",
    a3: "Two days ago",
    a4: "I don't know"
  }

  {
    q: "How much do you weigh today?",
    choicetype: "keypad"
  }

  {
    q: "Do you take any medications?",
    choicetype: "radio",
    a1: "Yes",
    a2: "No"
  }

  {
    q: "Which medications?",
    choicetype: "multiselect",
    a1: "Zostavax",
    a2: "Percocet",
    a3: "Actemra",
    a4: "Cimzia",
    a5: "Relprevv"
  }

];

选项2:

var hygiene = {

  pageheader: "Self-Care",

  question1: [
    "When was your last shower?", "radio", "Today", "Yesterday",
    "Two days ago", "I don't know"
  ],

  question2: [
    "How much do you weigh today?", "keypad"
  ],

  question3: [
    "Do you take any medications?", "radio", "Yes", "No"
  ],

  question4: [
    "Which medications?", "multiselect", "Zostavax", "Percocet",
    "Actemra", "Cimzia", "Relprevv"
  ]

};

2 个答案:

答案 0 :(得分:7)

我的建议不是使用它们中的任何一个,而是使用以下内容:

var hygiene = {

    pageheader: "Self-Care",

    questions: [

        {
            question: "When was your last shower?",
            choicetype: "radio",
            answers: [
                "Today",
                "Yesterday",
                "Two days ago",
                "I don't know"
            ]
        },

        {
            question: "How much do you weigh today?",
            choicetype: "keypad"
        },

        {
            question: "Do you take any medications?",
            choicetype: "radio",
            answers: [
                "Yes",
                "No"
            ]
        },

        {
            question: "Which medications?",
            choicetype: "multiselect",
            answers: [
                "Zostavax",
                "Percocet",
                "Actemra",
                "Cimzia",
                "Relprevv"
             ]
         }
    ]
}

答案 1 :(得分:1)

选项1比选项2好得多,因为您指定了变量并给出了每个字符串有意义的名称,以便稍后在代码中使用。

如果您有大量的问卷,这取决于您的代码的可读性。如果你在文件中有100个,你更喜欢1还是2?