简体   繁体   中英

JavaScript syntax issue: [{ }] hierarchy

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?

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.

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 eg 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只是对象的数组,是的,这是常见的做法。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM