Populating an array using while loops

My attempt to populate "array1" with numbers from 1 to 10 seems to be failing.

array1 = ["123", "abc", "string", "text", "test", "ok"]
                 while (i <= 10){
                    array1.push(i)
                    i++
                 }
    document.getElementById("p0").innerHTML = document.getElementById("p0").innerHTML + " | " + array[Math.floor((Math.random() * array.length))]

No matter what, the innerHTML of p0 remains as "Random Array Item:" and doesn't change. However, if I remove the while loop, it works fine, displaying output like this: "Random Array Item: | test | text | abc | abc | text | abc"

Answer №1

There seems to be an error in your code where you are referencing the wrong array name. Instead of using array, make sure to use the correct array name which is array1. This adjustment should resolve the issue:

i=0;
array1 = ["123", "abc", "string", "text", "test", "ok"];
while (i <= 10){
    array1.push(i);
    i++;
}
document.getElementById("p0").innerHTML = document.getElementById("p0").innerHTML + " | " + array1[Math.floor((Math.random() * array1.length))];
<p id="p0">Random Array Item</p>

Answer №2

If you simply need to populate a new array with the numbers 1 through 10, this code snippet will do the job.

let initialArray = ["apple", "banana", "cherry", "date"],    
[1,2,3,4,5,6,7,8,9,10].forEach(function(num){
 initialArray.push(num);
});

document.getElementById("result").innerHTML = document.getElementById("result").innerHTML + " | " + initialArray[Math.floor((Math.random() * initialArray.length))];

Answer №3

Make a few tweaks:

let x = 0;
dataSet = ["apple", "banana", "pear", "orange", "kiwi"]
             while (x <= 10){
                dataSet.push(x)
                x++
             }
document.getElementById("p0").innerHTML = document.getElementById("p0").innerHTML + " | " + dataSet[Math.floor((Math.random() * dataSet.length))]

Essentially, you just have to update the variable name from array to dataSet.

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

What is the process for setting up redux in _app.tsx?

Each time I compile my application, I encounter the following error message: /!\ You are using legacy implementation. Please update your code: use createWrapper() and wrapper.useWrappedStore(). Although my application functions correctly, I am unsure ...

AngularJS Assessing an Attribute directive following an Element directive

Currently, I am utilizing an angular plugin that can be found at the following link: https://github.com/angular-slider/angularjs-slider The objective is to customize the "legends" produced by the directive. In order to achieve this customization, the dire ...

Run JavaScript on every website when the page loads

After loading all or specific pages in the browser, I am looking to run JavaScript code (predefined code). Are there any browsers and plugins/components that allow me to achieve this? The manual method involves opening the console (e.g. firebug) and execu ...

Is it possible to generate output using multiple screenshots extracted from a JSON file, such as the iTunes Search API?

Is there a way to create a loop and display one or more jpg screenshot URLs from the JSON variable "screenshotUrls"? $.getJSON("https://itunes.apple.com/lookup?id=343200656&callback=?", function (data) { var icon = document.getElementBy ...

Getting an invalid ELF header error when using nodejs iconv

Just checking on my local computer (mac terminal, with node web.js) I confirmed that it is running on the local server. However, every time I try to deploy it to the server, I keep getting this error message: Error: /home/hosting_users//apps//node_modul ...

Unable to access input field value through PHP $_POST array

Having trouble retrieving the value of $_POST['value'] after submitting a form. Implemented a JavaScript function to set a value for an input field. code: function updateValue(pid, value){ // called from a popup window to update the field w ...

Ways to stop the location object from resetting in ReactJS when reloading the page

Currently, I am using Link to redirect and call another component. The code looks something like this: <Link to={{ pathname: "/app/" + app.appId, appDetail: { app: app } }}>> When I call the path /app/:appId, it triggers the AppDetails ...

Ways to halt the setInterval function after executing a specific function within it

Currently, I have a condition in place to verify if I am on a specific URL. If this condition is true, the setInterval() function will begin checking for a particular element on the webpage. Once the element is located, a designated function will be exec ...

Tips for troubleshooting PHP errors while making a jQuery AJAX request

My dilemma involves an HTML form that I submit to a PHP server. When I submit the form using a standard method with a submit button and the action set to "screen_custom.php", everything works perfectly fine. I receive a page filled with valid JSON data. H ...

Using MongoDB's .NET Driver pullFilter function to eliminate a string from a string array

I've been attempting to use a pullFilter on complex types but facing some challenges with removing values from an array. await _Collection.UpdateOneAsync( Builders<Descriptor>.Filter.Eq(d => d.Id, id), Builders<Descriptor>.Update .S ...

Is there a way for me to generate a tab that shows content when hovered over?

Is it possible to create a tab that displays a vertical list of redirections when the mouse hovers over it, and hides when the mouse is moved away? This seems like a challenging task. Can someone guide me on how to achieve this, especially if it involves ...

React Form with Conditional Input Options and Validation

Just diving into the world of React, I find myself connecting a React frontend to a Flask backend in a group project. Surprisingly, I've ended up handling about 90% of the workload. While I have utilized MUI for implementing fields, my focus is more o ...

Managing two variables in C# Controller and View

I am facing an issue with the two variables in my controller class. The first variable, currentUserId, is supposed to store the user currently logged into the website. The second variable, currentRoomId, should track the chat room the user is in. The probl ...

Is there a way to invoke a function within an Angular Service from within the same service itself?

Below is the code snippet I am working with: angular.module('admin') .factory('gridService', ['$resource', 'gridSelectService', 'localStorageService', function ($resource, gridSelectService, ...

Tips for creating clickable selections with AutoComplete JQuery in ASP.NET and C#

Currently, I am working on a project that involves implementing AutoComplete functionality in a textbox using JQuery AutoComplete. I have included the following file: jquery-ui.js The goal is to make the matched text appear in bold. For example, if I typ ...

Ways to resolve a 500 internal error

I have created an online test system for students, but I am facing an issue with passing answers in JSON format. Whenever I attempt to do so, I encounter a 500 internal error and I am unable to identify the root cause. Even after removing lengthy JSON dat ...

Instead of scrolling through the entire window, focus on scrolling within a specific HTML element

I currently have the following elements: #elementA { position: absolute; width: 200%; height: 100%; background: linear-gradient(to right, rgba(100,0,0,0.3), rgba(0,0,250,0.3)); z-index: 250; } #containerofA { position: fixed; ...

Issues arise when attempting to use custom Javascript functions in conjunction with the Bootstrap 4 Input Tagging Plugin

Currently, I am utilizing the Bootstrap tags input plugin to create tags within a text input on my HTML page. However, I am encountering difficulties in executing Javascript functions that should be activated when the input field is clicked while using thi ...

Deliver search findings that are determined by matching criteria, rather than by identification numbers

I am seeking to return a JSON match upon form submission, rather than simply searching for a specific ID. However, I am uncertain about how to structure this. I have the ability to search for the necessary match in a JavaScript document within one of my n ...

A guide to determining the dimensions (width, height, length) of a mesh using THREE.js

I've been scouring different sources in hopes of finding a way to obtain the width and height of a mesh, but I haven't had any luck. I have imported a collada model into my project, and all I need is to determine its dimensions in Webgl/Three.js ...