尝试从对象内部的数组中引用多个元素

时间:2018-12-15 20:29:20

标签: arrays object

我有一个对象,该对象具有包含多个对象和数组的数组。 我一直试图弄清楚如何一次引用多个元素,但是找不到方法。

  var questions =  {
  options : [{
  question : "Only one province is oficially bilingual, can you guess which 
  one?",
  choices : ["Quebec", "British Columbia", "Manitoba", "Newbrunswick"],
  answer : 3
  },

  {  question : "Which canadian city is considered The Hollywood North?",
  choices : ["Manitoba", "Vancouver", "Beamsville", "Niagara Falls",],
  answer : 1
  },

  {  question : "What is the capital of Canada?",
  choices : ["Ottawa", "Toronto", "Vancouver", "Edmonton"],
  answer : 0
  },

  {  question : "What are the official winter and summer sports of Canada?",
  choices : ["Ice hockey and lacrosse", "Boxing and Baseball", "Skiing and 
  Swimming", "Football and Tennis"],
  answer : 0
  },

  {  question : "How many time zones does Canada Have?",
  choices : ["4", "3", "5", "6"],
  answer : 3
  },

  {  question : "What animal is on the Canadian quarter?",
  choices : ["Whale", "Polar Bear", "Caribou", "Beaver"],
  answer : 2
  },

  {  question : "What is the Canadian $1 coin called?",
  choices : ["Moonie", "Dolly", "Loonie", "Toonie"],
  answer : 2
  },

  {  question : "What is the leader of Canada called?",
  choices : ["Queen", "Prime Minister", "King", "President"],
  answer : 1
  },

  {  question : "What is the name of the highest mountain in Canada?",
   choices : ["Mount Logan", "Mount Carleton", "Mount Saint Elias", "Mount 
  Columbia"],
  answer : 0
  }
  ]};

我尝试过:

   console.log(questions.options[0].question);
   console.log(questions.options[1].question);
   console.log(questions.options[2].question);  
   //etc...

是否可以通过一个console.log显示所有问题?我猜想for循环会做到这一点,但我无法弄清楚。提前谢谢。

1 个答案:

答案 0 :(得分:0)

您可以执行以下操作:

questions.options.forEach(function(item) {
    console.log(question.question);
});

或者如果您只希望一个字符串引用所有项目:

var allQuestions = questions.options.reduce(function(all, current) { 
    return all + ' - ' + current;
})