Dealing with undefined array sizes in Javascript

I'm struggling to populate an array using a while loop. Even though the length of the array indicates that there is data present, attempting to access the data at specific indices returns undefined.

  var test = [];
  while (i < 16)
  {
    test[i] = i;
    i++;
    console.log(test.length);
    console.log(test[i]);
  }

Console output:

1
Fibbo.html:48 undefined
Fibbo.html:47 2
Fibbo.html:48 undefined
Fibbo.html:47 3
Fibbo.html:48 undefined
Fibbo.html:47 4
Fibbo.html:48 undefined
Fibbo.html:47 5
Fibbo.html:48 undefined
Fibbo.html:47 6
Fibbo.html:48 undefined
Fibbo.html:47 7
Fibbo.html:48 undefined
Fibbo.html:47 8
Fibbo.html:48 undefined
Fibbo.html:47 9
Fibbo.html:48 undefined
Fibbo.html:47 10
Fibbo.html:48 undefined
Fibbo.html:47 11
Fibbo.html:48 undefined
Fibbo.html:47 12
Fibbo.html:48 undefined
Fibbo.html:47 13
Fibbo.html:48 undefined
Fibbo.html:47 14
Fibbo.html:48 undefined
Fibbo.html:47 15
Fibbo.html:48 undefined
Fibbo.html:47 16
Fibbo.html:48 undefined

Answer №1

To resolve the issue, you need to adjust your code as follows:

  let i = 0;
  const testArray = [];
  
  while (i < 16) {
    testArray[i] = i;
    console.log(testArray.length);
    console.log(testArray[i]);
    i++;
  }

Answer №2

Make sure to update your code like this:

let numbers = [], index = 0;
while (index < 16)
{
    numbers[index] = index;
    index++;
    console.log(numbers.length);
    console.log(numbers[index-1]);
}

The value of 'index' was being increased after assigning a value to it.

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

How can you include a comma between two objects within a string, excluding the last object, using JavaScript?

I have a string object stored in a variable passed from another class. My question is how can I add a comma between two objects, excluding the last object? Below is my code snippet: { "id":"57e4d12e53a5a", "body":"asdas", "publishe ...

Node.js and Express: tackling the problem of duplicate variables

I have a checkUser middleware that saves the user information when a JWT is verified. However, when I integrate it into my routes and attempt to log res.locals.user.username, the username appears twice in the console. This duplication is causing issues wit ...

Meteor is not recognizing the defaultValue property in React

I'm puzzled by this issue—it's frustrating that it's not working as expected. <input type="text" id="first_name" name="first_name" className="form-control" defaultValue={this.props.user.first_name} required/> However, I've di ...

Autocomplete appears to be malfunctioning

Currently, I am in the process of creating a website to enhance my coding skills. One of the features I am working on is an autocomplete functionality that is built using Jquery UI. The data for this autocomplete is being fetched from three MySQL tables. ...

Tips for avoiding image flickering when refreshing the URI in a React Native app

How can I prevent unwanted flickering when a new image src is being loaded as a socket response that reloads multiple times in a second? ...

Securing socket.io connection in a nodejs application

I'm currently developing a chat application that utilizes sockets for bi-directional message sharing. Although the socket is functioning properly, I would like to implement user authentication before granting access to the socket connection. I'v ...

Using onClick function to pass the value of an input textbox in PHP

I have an input text field and I am looking to pass the values entered inside the element through a JavaScript onClick event. <form> <fieldset> <label>Common Site ID: </label><span><?php echo $commonsiteid ?>< ...

ISO format for the number of weeks in a month, considering weeks that cross over Thursday

I am looking for a precise number of weeks per month in accordance with the ISO standard. Instead of using JavaScript's Date, I am utilizing momentJS. According to the ISO date format, a month's week count is determined based on whether it cont ...

What could be causing JQuery to concatenate the string twice?

Looking for a way to trigger the playback of a YouTube video embedded within a div named #youtubecontainer after a button click with the class .playbutton. The video itself is embedded as an iframe within the specified div. One way to make this work is b ...

PHP Array Element Output

After making a call to the Twitter API, I have received an Array of data containing the "Top 10 Trending" items. However, I am facing difficulty in printing out the individual elements such as names. Below is the code snippet that I have been using to disp ...

Using Angular to generate a dynamic placeholder text

After doing some research, I came across several resources that reference 'ng-placeholder' or a similar term. Despite my efforts, I am unable to make it work: <input type="text" placeholder="{{option.name}}" class="form-control" ng-switch-whe ...

Verify whether the combined total of two elements sharing the same identifier is less than zero

I am working with two 2D arrays: illustration arr1 = [['2001-01-01', 100], ['2001-01-02', 105],...] arr2 = [['2001-01-01', 100], ['2001-01-02', 120],...] query I want to determine if subtracting any of the [i][ ...

Including file format extension in the absence of one

I have created a script that loops through every image source on the page, extracting the extension. If the extension is not recognized or does not exist, I automatically add .jpg to the end. Strangely, the if statement always evaluates to true no matter ...

Trigger a function post-rendering in a React component

Hey everyone, hope you're having a great day! I've been diving into React for a few months now. I'm making an effort to steer clear of using the traditional React Components, opting instead for React Hooks. However, there are instances wher ...

Sending an ajax request to submit the results of jQuery.each loop

$(".submitinfo").each(function() { // Using ID as POST name and value as POST value }); // Sending the data using ajax request $.ajax({ url: 'submit.php', traditional: true, data: { 'submit':'true', 'age&a ...

Transform a complex PHP array into JSON format using JavaScript

I have a three-tiered PHP array with both numeric indices and key-value pairs. I would like to convert it to JSON, and reiterate through the object list. How would I do this? The PHP array is called $main_array, and appears as: Array( [0] => Arra ...

Issue with Mongoose query for finding data in multiple columns

If a keyword matches in category.title, then it will provide a result; otherwise, it does not match with any other fields. Can someone point out what the issue might be here? I also attempted NewsModel.find().or(filters) without the $or key, but it still i ...

I'm trying to access my navigation bar, but for some reason, it's not allowing me to do so

Having trouble getting the navigation bar to open. I have set it up so that when clicked, it should remove the hide-links tag, but for some reason, it does not toggle properly and keeps the ul hidden. import React from "react"; import { NavLink } ...

Tips for setting up the information in a Bootstrap popover

I am currently working on a Google web app that involves Google Sheets data. My objective is to have the data displayed when hovering over a button, but instead, the data appears directly on the button without the hover display. What might I have done in ...

Having received a status code of 200 in Flask WebApp, I am still unable to access the page

Currently in the process of developing a webapp using Flask, I have created the homepage where users are required to input their phone number and password. Once entered, the system will send an OTP to the provided phone number. When clicking the signup bu ...