The looping mechanism results in only displaying the final number

Through my coding journey, I crafted a for loop to showcase multiple entries stored within an array. Unexpectedly, the for loop only displays the final entry in the array as opposed to all elements from the beginning to the end.

for (var i = 0; i < roa.length; i++) {questionContentRoa = roa[i].questionContent, correctAnswerRoa = roa[i].correctAnswer }
                console.log(questionContentRoa, correctAnswerRoa);

Answer №1

Enhancing code readability can be achieved by properly indenting the code.

The console.log statement is positioned outside of the loop's scope, causing it to only display the last assignment before the loop concludes.

for (var i = 0; i < roa.length; i++) {
    questionContentRoa = roa[i].questionContent;
    correctAnswerRoa = roa[i].correctAnswer;
}
console.log(questionContentRoa, correctAnswerRoa);

Answer №2

You seem to have placed the console.log outside the for loop when it should be inside.

Another approach to looping through an array is to use the forEach method.

roa.forEach((item)=>{
console.log(item.questionContent, item.correctAnswer );
}); 

// item represents each element in the array during each iteration

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

Manipulating global state properties within a reducer function in React: How to do it efficiently

I am looking to implement a single loader (backdrop and spinner) within my app component that can be displayed based on the value of a property in the Redux state called showLoader. This loader should be accessible throughout my entire React application. T ...

Perform a function dynamically once a specific textfield is filled and continuously while filling another textfield

Imagine we have two text fields - one for a first name and one for a surname. As I type in the surname field after already filling out the first name, a function called sug() should provide suggestions or perform some action each time I add another letter ...

Alter hyperlink colors according to <spans>

I am looking to customize the color of links in a chat transcript. Specifically, I want to change the links that the customer sends to red, while keeping the links sent by the agent in blue. Can someone provide guidance on how to achieve this using CSS or ...

Enable automatic playback of HTML5 video with the sound on

I want to add an autoplay video with sound on my website, but I'm running into issues with newer browsers like Chrome, Mozilla, and Safari blocking autoplay if the video doesn't have a 'muted' attribute. Is there a clever HTML or Javas ...

Locate commas within quotation marks using regex and replace them with their corresponding HTML entity

When dealing with a string like this: "Hello, Tim" Land of the free, and home of the brave I want it to be transformed into: "Hello&#44; Tim" Land of the free, and home of the brave This should be a simple task, but I'm struggling to find th ...

How to retrieve an element from an array within an object by utilizing v-for in Vue.js

Currently, I am working on displaying the names of each budget by using v-for. I have a vuex getter set up to retrieve the budgets associated with a user; however, it returns each object within the array. How can I specifically access the name of each budg ...

Explaining the functionality of a for loop with a vector in R

I recently encountered a challenge while working with for loops for a vector in R. Although I managed to find a solution, I'm still puzzled about the underlying mechanics. While developing a function, I faced an issue where the for loop was only iter ...

keep information separate from a react component and generate state based on it

Is it considered acceptable to store data outside of a react component and update it from within the component in order to derive state? This method could be useful for managing complex deep-nested states. import React from "react"; let globalSt ...

Can PHP encode the "undefined" value using json_encode?

How can I encode a variable to have the value of undefined, like in the JavaScript keyword undefined? When I searched online, all I found were results about errors in PHP scripts due to the function json_encode being undefined. Is there a way to represent ...

Updating multiple array elements in MongoDB

Recently, I came across a document that has the following structure: { codeId: 1, generatedCodes: [ { name: 'Code 1', status: 'In Progress' }, { name: 'Code 2', status: 'In Progres ...

Struggling with making the Angular directive compatible with ng-container

Below is the code snippet where the ng-if condition is not behaving as anticipated If the value of displayGroup is D, it should display the first and second blocks. Can you spot any error in my logic? <div *ngIf="(bookTravelInfo.displayGroup | upp ...

Incorporating Unique Typography with Typekit/Adobe Fonts in Tiny MCE editor within a React

I'm currently working on integrating a custom Adobe Typekit font into a TinyMCE React component to customize the text styling within the editor. Here is the setup I have: <Editor init={{ allow_html_in_named_anchor: false, ...

How is it that the `chrome.tabs.create` function is able to create a tab and set it as active on mobile Chromium browsers despite passing active: false as a parameter

I am currently developing a MV3 Chromium extension. In this extension, I am trying to implement a feature where a new tab is created using chrome.tabs.create and the user is directed to a specific site. The main requirement is for the new tab to open in th ...

Concealing choices that have already been chosen in a ReactJS select dropdown menu

My challenge involves having 3 select boxes with the same option values, where users set security questions. Each question is selected and answered by the user. I fetched security questions via an API call and stored them in an array named "securityQuestio ...

Order of Execution

I am facing an issue with the order of execution while trying to retrieve values from my WebApi for input validation. It appears that the asynchronous nature of the get operation is causing this discrepancy in execution order. I believe the asynchronous b ...

Scaling a mesh and BufferGeometry vertices using THREE.OBJLoader

Utilizing the THREE.OBJLoader, I successfully loaded a 3D model into my scene. Subsequently, I have the necessity to scale it by 10 and then extract its vertices position. I am aware that the THREE.OBJLoader provides a BufferGeometry, allowing me to acce ...

A comparison between the Composition API and traditional Plain JavaScript syntax

I'm currently exploring the necessity of utilizing the 'new' Vue Composition API. For instance, take the following component extracted from their basic example: <template> <button @click="increment"> Count is: {{ ...

Error occurs when plotting an array of values against dates using numpy

I have recently made changes to my code and added comments for sharing purposes. I am still new to numpy and struggling to understand why I am unable to plot the data. The data consists of properly formatted dates compared to floating point numbers. If an ...

"JavaScript: An In-Depth Guide on Iterating Over Objects Using

I am trying to iterate through the req.body payload object in a nodejs application and extract the array object with SplitType = 'FLAT'. However, when I attempt to loop through the array object, I encounter an error stating that SplitType is unde ...

Numerous XMLHttp requests causing JSON data to be overwritten

I am facing an issue where my JSON data is being overwritten by the result of the last XMLHttpRequest made for each country. Is there a way to prevent this from happening? Below is the code snippet in question: function getDataBetween() { for (var i = ...