Strategies for Iterating Through Array Elements Multiple Times

When I want to log the numbers one to five just once, I usually use code like this:

var array = [1,2,3,4,5]

function loop(n) {
  for (var i=0;i<n;i++) {
    console.log(array[i])
  }
}

loop(5)

However, if I want to log the numbers one to five multiple times, how can I achieve that?

For example, by calling loop(10); I expect to see the following output: 1 2 3 4 5 1 2 3 4 5

Currently, when I call loop(10), I only get 'undefined' after the initial loop of 1 to 5.

Answer №1

Implement the modulo operator :

function iterate(n) {
  for (var i=0;i<n;i++) {
    console.log(list[i%list.length])
  }
}

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

The VueJS v-bind attribute doesn't always reflect changes right away following an AJAX request

In the table, each row corresponds to an event. The events have timeslots rendered as span elements, and each timeslot is assigned the na class through v-bind only when its stopsales property is true. The timeslots are fetched asynchronously from an ajax ...

Unable to retrieve the most recent global variable value within the confirmation box

<script type="text/javascript"> var customDiv ="hello"; $(function () { var $form = $("#authNotificationForm"); var startItems = $form.serializeArray(); startItems = convertSerializedArrayToHash(startItems); $("#authNoti ...

The state object in Next.js appears to be missing

const [ values , setValues ] = React.useState({ input_type: '', elements: [] }) const addOption = () => { let newElements = values.elements newElements.push({ type: "option", ...

Retrieving an array of objects through an Angular service

I'm fairly new to Angular and Javascript. Recently, I created an Angular service that fetches an array of users from an HTTP call returning JSON data. While the HTTP call is successful and returns the correct data, I'm having trouble passing this ...

Retrieving a value attribute from the isolated controller of a directive

I have a directive that reads and writes attributes, but I'm having trouble getting it to work as expected. The issue seems to be with the controller inside main-directive.js, which is empty, while the actual action is happening in the isolated direct ...

How can one authenticate an express session when sending a POST request?

Is there a way to verify that a user is sending a post request in order to prevent unauthorized posting to a URL? I am currently using express-session for this purpose, but I'm open to exploring alternative methods as well. I attempted to implement t ...

Leverage the power of JSON data in conjunction with HighCharts through

I'm struggling to understand the JSON format and HighCharts. Despite trying various techniques found on forums, I haven't been able to achieve the desired result. Here's my issue: 1- When clicking, an Ajax call is made to a PHP file that g ...

Gradually bringing a tag into view, gently fading it away, and then altering the text before beginning the cycle anew

I have a situation where an tag's content is being dynamically changed with jQuery and then faded in and out using the Velocity JS library along with the setInterval function. Initially, everything works smoothly for about 30 seconds. However, after ...

Issue with background overlapping

I am currently creating a questionnaire that consists of 10 questions and calculates a score called total. If the total < 10, I want the screen to turn red. However, this required me to remove the previous wallpaper that was set: /*body{ backgr ...

Experiencing difficulties with using the javascript alternative to jQuery.ajax()

Here is a JavaScript Object: const data = { name: "John", age: 30, } const jsonData = JSON.stringify(data); The AJAX Request below successfully passes the data: $(function(){ $.ajax({ url:'two.php', ty ...

The jQuery Deferred feature on Ajax is failing to properly pass the array in the data option as an array, instead converting

I am facing an issue in my application where I want to use jQuery deferred to handle Ajax success and error uniformly from a central location. It works perfectly fine when I pass strings in the data option, but when I try to pass an array, it gets sent as ...

Display a loading indicator while rendering several Vue components

My current challenge involves loading multiple Vuetify card components based on the selected category at the top of the page. The issue arises when the array renders more than 50 cards, causing a significant delay in loading time. While I am not overly co ...

ClickEvent (or element selector) is experiencing functionality issues

I'm currently working on creating a small calculator using HTML, CSS, and JS. However, I'm facing an issue with selecting buttons of the calculator from the HTML script and adding EventListeners to them. Here is a snippet of my HTML code: `< ...

Angularjs search filter performance slows down significantly when handling large datasets

I am currently working on an AngularJS client application that displays data in a table using the dir-paginate directive from dirPagination.js. Here is the code snippet: <input type="text" ng-change="SomeTask()" ng-model="vm.searchKeyword" /> &l ...

Planes in Three.js that are overflowing may have their opacity adjusted

My current challenge involves aligning two planes in the same (or closest possible) position. When two planes made of different materials and colors occupy the same space, depending on the camera angle and view perspective, the front plane's opacity ...

Encountering an error with ResizeObserver.observe when using Next.js and ag-grid to render client side

I designed a product page that includes a searchbar component and a grid component with the ag-grid import and setup. Here is a simplified version of the product page: // Code for dynamic client side rendering import const ProductGrid = dynamic(() => ...

Attempting to deploy a GitHub repository onto Railway.app has led to an Application Error. It seems like the issue may lie in whether your app is

I encountered an Application Error while deploying my project to railway.app. The error message prompts, "Is your app correctly listening on $PORT?". Initially, my project was a combination of JS and jQuery. However, I later integrated webpack.config.js t ...

After the "div" tag comes the magic of AJAX, PHP, and JAVASCRIPT, replacing

My Ajax implementation is successfully displaying the selected content on a div, but unfortunately, everything that comes after the div is getting replaced by this output. I am unsure of why this is happening and how to resolve it. If you have any insigh ...

Display a pop-up message asking for confirmation within a set duration?

Is there a way to display a confirmation dialogue that is set to expire after a certain time, triggering one of two actions if the user does not respond? Specifically, the confirmation should expire if the user: a) navigates away from the page b) fails t ...

What is the best method for storing a 2D array in a Script Property using the Properties Service in Google Apps Script?

Can anyone provide guidance on how to save a 2D array as a property in Google App Script? var array = [['value 1', 1.0, 'A'],['value 2', 2.0, 'B'],['value 3', 3.0, 'C']] PropertiesService.getSc ...