具有多个值的JavaScript对象

时间:2015-04-28 00:25:08

标签: javascript object

我正在尝试为调查问卷建立一组问题和答案。每个实例都有一个id,一个css类,一个问题,以及至少一个答案。当有多个答案时,是否可以有多个值?

var qa = [
{id: "0", css: "multiple", question: "Do you own a home?", answers: "Yes", "No"},
{id: "1", css: "input", question: "Who will live in your home?", answer: "<textarea rows='5' class='textarea'></textarea>"}
];

1 个答案:

答案 0 :(得分:6)

您可以将答案转换为数组:

var qa = [{
            id: "0",
            css: "multiple",
            question: "Do you own a home?",
            answers: ["Yes", "No"]
}];

而不是像这样访问它:

qa[0].answers[0] // for "Yes"
qa[0].answers[1] // for "No"

qa[0]['answers'][0]// for "Yes"
qa[0]['answers'][1] // for "No"

或者您也可以使用对象代替数组:

var qa = [{
           id: "0",
           css: "multiple",
           question: "Do you own a home?",
           answers: [yes: "Yes", no: "No"]
}];

而不是像这样访问它:

qa[0].answers.yes // for "Yes"
qa[0].answers.no // for "No"

qa[0]['answers']['yes']// for "Yes"
qa[0]['answers']['no'] // for "No"