最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

JavaScript object with multiple values - Stack Overflow

programmeradmin4浏览0评论

I am trying to build a set of questions and answers for a questionnaire. Each instance has an id, a css class, a question, and at least one answer. Is it possible to have multiple values when there is more than one answer?

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>"}
];

I am trying to build a set of questions and answers for a questionnaire. Each instance has an id, a css class, a question, and at least one answer. Is it possible to have multiple values when there is more than one answer?

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>"}
];
Share Improve this question edited Apr 28, 2015 at 0:43 Ram 145k16 gold badges172 silver badges200 bronze badges asked Apr 28, 2015 at 0:25 Solona MeadSolona Mead 711 gold badge1 silver badge5 bronze badges 4
  • 10 Yes, by using arrays! ... answers: ["Yes", "No"] – Ram Commented Apr 28, 2015 at 0:26
  • Is the code in your question working or is it an example of what you are trying to acplish? – EternalHour Commented Apr 28, 2015 at 0:30
  • @EternalHour The code has a syntax error. So it's not working. – Ram Commented Apr 28, 2015 at 0:34
  • 2 Note that your question has nothing to do with jQuery. You have defined a JavaScript array. – Ram Commented Apr 28, 2015 at 0:44
Add a ment  | 

1 Answer 1

Reset to default 10

You can do this by turning the answers in to an array:

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

And than access it like this:

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

or

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

Or instead of an array you also can use an object:

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

And than access it like this:

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

or

qa[0]['answers']['yes']// for "Yes"
qa[0]['answers']['no'] // for "No"
发布评论

评论列表(0)

  1. 暂无评论