How to create a function that says whether or not the answers to a questionnaire are correct?

0

I'm trying to do a questionnaire like this

I create an array that contains the objects of my questionnaire inside

    var cuestionario = [{
    pregunta: 'pregunta1',
    opciones: {
      a: 'opcionA1',
      b: 'opcionB1',
      c: 'opcionC1',
    },
    correcta: 'a',
  },
  {
    pregunta: 'pregunta2',
    opciones: {
      a: 'opcionA2',
      b: 'opcionB2',
      c: 'opcionC2',
    },
    correcta: 'b',
  }

]

How can I create this function to check if the selected option is correct ?.

The parameter "Selected Option" is one of the Strings of the "Options" object.

function comprobarRespuesta(opcionSeleccionada) {

}

Is there any more elegant way to do this?

    
asked by Serux 12.03.2018 в 01:52
source

1 answer

1

As you have it raised seems simple enough, although surely your function also needs to receive either an index of the arrangement of questions or an entry of that arrangement so you know what question you are working with (unless the question current is stored in an external variable). In case the function also received the object with data of the question, the function could be posed as follows:

function comprobarRespuesta(entradaArreglo, opcionSeleccionada) {
    return entradaArreglo.opciones[entradaArreglo.correcta] === opcionSeleccionada
}

As you can see, the correctArray entry will contain a string corresponding to the correct option ('a', 'b' or 'c') and this string can be used as a key for the options object. obtain the concrete answer, so that it would only be necessary to compare said answer against the argument received.

    
answered by 12.03.2018 / 03:56
source