Pregunta

I came across the following nested array and am little confused as to why it uses this particular syntax:

var allQuestions = [{
   question: "Which company first implemented the JavaScript language?",
   choices: ["Microsoft Corp.", "  Sun Microsystems Corp.", "Netscape Communications Corp."],
   correctAnswer: 2
}];

Full example: http://jsfiddle.net/alxers/v9t4t/

Is it common practice to use [{...}] having declared a such a variable?

¿Fue útil?

Solución

The definition is an array with an object literal in it. It is not realy a nested array. The

{
 question: "Which company first implemented the JavaScript language?",
 choices: ["Microsoft Corp.", "  Sun Microsystems Corp.", "Netscape Communications Corp."],
 correctAnswer: 2
}

is an object literal, which your array contains. In the fiddle you linked to there are several of these defined in the allQuestions array. By doing this it makes it easy to loop over the array of questions and display each in turn.

Otros consejos

What's happening there is listing the object inside an array, example:

[{id:1, value:"any"}, {id:2, value:"any any"}]

So here we have declared array with two objects in it. Another so called "traditional" approach would be:

var arr = [];
var obj1 = {id:1, value:"any"};
arr.push(obj1);
...

The allQuestions variable is supposed to be "an array of questions", where each question is an object with properties like question, choices or correctAnswer.

If it was declared just as var allQuestions = {question: ..., choice: ...}, it would be just the one object. Further code which want to know the number of questions allQuestions.length or access e.g. the first question's test as allQuestions[0].question would not work.

Try adding more questions and you will see what the extra brackets are for:

var allQuestions = [
  { question: "1st...", ...},
  { question: "2nd...", ...},
  ...
];

allQuestions is just an array of objects and yes, it is common practise.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top