Can a for loop iterate through a conditional statement using the length property?

Glad you're here to check this out. See the code below.


let questions = [];

let Question = function(question, answers, number) {
    this.question = question;
    this.answers = answers;
    this.number = number;
}

let question1 = new Question('Is JavaScript the best programming language?', 
['No', 'Yes'], 1);

let question2 = new Question('Is JavaScript a web development language?', 
['No', 'Yes'], 1);

let question3 = new Question(`What is JavaScript's official server side 
application called?`, ['BootStrap', 'Python', 'Node.js'], 2);

questions = [question1, question2, question3];

Question.randomQuestion = function() {
    let randomNum = Math.floor(Math.random() * 3);
    let randomQuestion = questions[randomNum];

    return randomQuestion;
}

Question.display = function(randomQuestion) {
    console.log(randomQuestion.question);
    debugger;
        // Why does the conditional give me undefined?
        for (let i = 0; i < questions[i].answers[i].length; i++)
        console.log(`${randomQuestion.answers[i]}`);    
    }

I'm trying to find the answers property length in each iteration, but I keep getting an error that says answers is undefined. Any idea why this is happening and a better way to achieve this?

Answer №1

There seems to be a couple of errors in the code. When iterating through two arrays, it's necessary to use two loops. I've included a snippet of code below that I believe will be helpful :

let questions = [];

let Question = function (question, answers, number) {
	this.question = question;
	this.answers = answers;
	this.number = number;
}

let question1 = new Question('Is Python the best programming language?',
	['No', 'Yes'], 1);

let question2 = new Question('Is Python a web development language?',
	['No', 'Yes'], 1);

let question3 = new Question(`What is Python's official server side 
application called?`, ['Django', 'Flask', 'Node.js'], 2);

questions = [question1, question2, question3];

const randomQuestion = function () {
	let randomNum = Math.floor(Math.random() * 3);
	let randomQuestion = questions[randomNum];
	return randomQuestion;
}

const display = function (randomQuestion) {
	const random_question = randomQuestion();
	console.log(random_question.question);
	//debugger;
	// Why am I getting undefined for the conditional?
	// Display all questions and answers
	for (let i = 0; i < questions.length; i++)
		for (let j = 0; j < questions[i].answers.length; j++)
			console.log(`${questions[i].answers[j]}`);
	// Alternatively :
	questions.forEach(e => {
		console.log(e.question);
		e.answers.forEach(a => {
			console.log(a)
		})
	})
}

display(randomQuestion);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

approach for extracting values from nested objects using specified key

There are objects in my possession that contain various nested objects: let obj = { nestedObject: { key: value } } or let obj2 = { nestedObject2: { nestedObject3: { key2: value2 } } } and so on. Retrieving the values from these objects i ...

Guide to setting a default child route in react-router and updating the URL as needed

Currently, I am utilizing react-router v3 and have a segment of my routing code as follows: ... <Route path='dashboard' component={Dashboard}> <Route path='overview' component={Overview}/> <Route path='scan&apo ...

Jquery problem: dealing with empty spaces

I am working on a project where I need to use jQuery to disable specific input fields, like the following: $("input[value=" + resultId[i].name + "]" ).prop('disabled', true); $("input[value=" + resultId[i].name + "]" ).css({ 'background-col ...

Creating an executable JAR for your Next.js application: A step-by-step guide

Is there a way to ensure that my Next.js file can run seamlessly on any computer without the need for reinstallation of all modules? In my folder, nextjs-node, I have the following subfolders: components lib public node_modules page style package.json I ...

How come I'm unable to send the HTTP request contents as a response using express.js?

I'm currently in the process of setting up a basic web server using node.js and express.js. Essentially, I want the server to return the content of the request as a response. Below is the code I have implemented: const express = require('express& ...

My webpage layout doesn't quite accommodate my content, so I need to adjust it to be more zoom

Why does the page container load bigger than the html/body container in mobile mode, as shown in the photo? https://i.sstatic.net/fD1N4.png Here is my CSS: html { margin-top: 48px; width: 100%; } body { margin: 0; width: 100%; background: ...

Find the sum of every combination of numbers in the array

I've reviewed my code countless times and I'm stumped by the issue. My code is designed to calculate all possible sums of numbers within an array. It works perfectly when there are only 3 numbers in the array, but once I add a fourth number, it i ...

Error: The function $(...).live is not defined within the MVC framework

I included a dialog box using jQuery in my MVC form. Here is the code snippet from my View : <link rel="stylesheet" href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css"> <script src="//code.jquery.com/jquery-1.10.2.js"></scr ...

Avoiding console errors when a REST call fails

After conducting some research, it appears that achieving this is not possible. Therefore, I decided to seek advice. My current task involves making a REST GET call to check for the existence of a folder. If the folder does not exist, I create a new one; ...

Using C# Razor Pages to send checkbox values via AJAX requests

In my model class, I have the following: public class DataModel { public bool Display { get; set; } } After deserializing a FormData object to a JSON object, I am posting the value from a checkbox like this: this.FormToJSON = form => { const ...

Manipulating arrays and troubleshooting Typescript errors in Vue JS

I am attempting to compare the elements in one list (list A) with another list (list B), and if there is a match, I want to change a property/field of the corresponding items in list B to a boolean value. Below is the code snippet: export default defineCo ...

Showing JSON response on an HTML page using AngularJS

I have limited experience with JavaScript and/or Angular, but I am required to utilize it for a research project. My task involves showcasing the JSON data returned by another component on a webpage. Here is how the process unfolds: When a user clicks on ...

How can one transform an array (in the form of a JSON array) into a map?

After running my script, I receive an array (JSON Array) structured like this: [{redirectCount=0, encodedBodySize=60962, unloadEventEnd=0, responseEnd=1601.699999999255, domainLookupEnd=995.7999999896856, ... Now, I want to display the key-value pairs fr ...

Tips for managing and capturing errors in Express

const database = require('database'); const express = require('express'); const app = express(); const cors = require('cors'); app.use(cors()); const bodyParser = require('body-parser'); const urlencodedParser = body ...

Utilizing the "apply" method with JavaScript OOP callbacks for dynamic context management

Encountering an issue while creating a callback in my custom EACH function utilizing Object-Oriented Programming principles. To achieve this, I have developed a JavaScript library that emulates the familiar habits of JQUERY. Experience it in action by ch ...

How to include <li> in a preexisting <ul> using JSON data in jQuery

Here is the code snippet I am currently working with: <div id="tags"> <ul> </ul> </div> I want to add some items to the list using JSON data $.getJSON("data.json", function (data) { var html = ''; ...

Cannot adjust expiration date of express-session in browser

In my current project, I am utilizing express-session. Let's say a session has been created between the web browser and the Node.js server with a default expiration time of one hour. At this point, there is a cookie named connect.sid stored in the use ...

Fetching weather data from the Darksky.com API in JSON format

My goal is to retrieve weather data in JSON format from the Darksky.com API. To do this, I first successfully obtained my latitude and longitude using the freegoip.com API. However, the Darksky API requires both longitude and latitude before it can provid ...

Error message: A state has not been defined within the onload function

I'm facing an issue where I am attempting to assign a data URL of an image to a state in Vue.js, but it is not getting assigned properly. After converting a blob URL to a data URL, the state does not contain the correct data URL. While the imgSrc doe ...

Reliable selection menu for changing fields

Can someone help me with this coding issue? I am attempting to create a dependent dropdown menu where selecting a category will also display relevant equipment. However, in my current setup, only the category field is functioning properly. When I try to a ...