Receiving an unanticipated value from an array

Actions speak louder than words; I prefer to demonstrate with code:

//global variable
var siblings = [];

var rand = new Date().getTime();
siblings.push('uin_' + rand);
alert(siblings['uin_' + rand]); // undefined

Why is it coming up as undefined? My main goal is to create a global object that acts as a storage for information about other objects. Going back to my issue... I added the value, then tried to alert it but it's showing as undefined... why?

Answer №1

.push adds the element to the array, siblings[0] stores it as the first element in the previously empty array.

If you prefer to choose the key yourself, you can:

siblings = {};
siblings['key'] = 'something';

Otherwise, iterate through the array to access each element:

for ( var l = siblings.length, i = 0; i<l; ++i ) {
   alert( siblings[i] )
}

Note: arrays are objects, so technically I could have used siblings['key'] = 'something'; on the array, but it's not recommended.

Answer №2

family is a collection of objects. You should not use an array for this purpose. Instead, you can create an object and assign key-value pairs to it.


var family = {};
var uniqueId = +new Date();
family['person_' + uniqueId] = "John Doe";
alert(family['person_' + uniqueId]);

Answer №3

By inserting a string into the first position of the array, you subsequently attempted to access a property that does not exist on the array object.

Consider utilizing Array.pop() as an alternative approach.

Answer №4

To tap into an array, you must utilize array indices, which essentially dictate whether you are seeking the 1st, 2nd, 3rd, etc., element.

For this scenario, employ siblings[0].

Answer №5

Due to the fact that siblings is an array and not an associative array, there are two possible solutions:

// Declaring a global variable as an array
var siblings = [];

var randNum = new Date().getTime();
siblings.push('uin_' + randNum);
alert(siblings[0]); // Will return undefined

// Declaring a global variable as an associative array
var siblings = {};

var randomNumber = new Date().getTime();
siblings['uin_' + randomNumber] = 'some value';
alert(siblings['uin_' + randomNumber]); // Will return 'some value'

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

Managing a database update when server actions involve various form types

My UI dashboard contains multiple forms like "edit title" and "edit description", each with just one input element. I am looking to streamline database updates and server actions in next js 14, utilizing useFormState on the front end. While I have achieve ...

I aim to utilize vanilla JavaScript in order to remove the parent element of the button being clicked when the user interacts with it

My latest project involves a meme generator that allows users to input text and images, which are then combined to create a unique 'meme'. Each meme is assigned a unique ID and features buttons for deleting the meme upon hovering. To achieve this ...

Why is my v-model not being updated when using a radio button in Vue.js?

After reviewing the documentation, I attempted to implement the code provided. While I am able to successfully retrieve data for enquiryDesc, I am consistently getting a value of 5 for the rating field. I even experimented with changing the radio group to ...

Utilizing API to Save Images Directly from the Client Side

I am currently in the process of redesigning a website, specifically the Blog section which includes a featured image. I have been researching the best method for saving these images. After following a tutorial that utilized the file.mv() function from ei ...

Disable the ability to select text when double-clicking

Is there a way to prevent text selection on double click while still allowing selection on mouse drag? Whenever I try to remove selection on dblclick or mouseup, it flashes, which is not the desired outcome as shown in this jsfiddle. UPD: I am not lookin ...

Accept a JSON-sending POST request in a JSP file via JavaScript

I have developed an HTML page with an input field. Using javascript, I extract the input value, convert it into JSON format, and attempt to send it through ajax. Additionally, I have a JSP application where a Java method processes this JSON data to store i ...

The data structure '{ one: string; two: string; three: string; }' cannot be directly assigned to a 'ReactNode'

Here is the Array of Items I need to utilize const prices = [ { name: "Standard", price: "149EGP", features: [ { one: "Add 2500 Orders Monthly", two: "Add Unlimited Products And Categories", three: "Add 20 other ...

Having difficulty including the Column Name in the Jqgrid footer for sum calculation

I was working on the Jqgrid code and found a way to display the sum correctly in the footer of the grid. var colSum = $("#dataGrid").jqGrid('getCol', 'Amount', false, 'sum'); $("#dataGrid").jqGrid('footerData', &a ...

The outcome of Contains function is coming back as negative

Recently, I was working on a project that I cloned from GIT, which involved a bot. However, I encountered an issue where the 'contains' function used by the bot was not functioning properly. After conducting some research using Google, I discove ...

Having trouble getting Bootstrap's Javascript to function properly in a Rails 6 webpacker configuration?

Recently initiated a brand new Rails 6.0.3 project and integrated jQuery and Bootstrap into it. Surprisingly, jQuery is functioning smoothly, and the Bootstrap CSS appears to be rendering correctly. However, every attempt to execute $.fn.tooltip.Construc ...

passing a javascript variable to html

I am facing an issue with two files, filter.html and filter.js. The file filter.html contains a div with the id "test", while the file filter.js has a variable named "finishedHTML." My objective is to inject the content of "finishedHTML" into the test div ...

Unveiling the enigma of unresponsive Bootstrap dropdowns

I'm working on creating a custom navigation bar using Bootstrap v5. I found the code on the Bootstrap website and copied it into my project. However, I also added some JavaScript code to enhance its functionality, but unfortunately, it's not work ...

What is the best way to eliminate all instances of the period symbol from an array?

How can I eliminate all instances of . from my array? var arr = ['...my name is apple', 'my girl .... friend is banana.......']; Below is the code snippet I am currently using. var arr = ['...my name is apple', 'my g ...

Storing information in a PHP database

I have created two pop-up divs on my website. Initially, the first div - div1, is displayed and it contains dropdown menus. Inside this div1, there is a button called Next which, when clicked, closes the first div and opens the second div; div2. Div2 consi ...

Am I going too deep with nesting in JavaScript's Async/Await?

In the process of building my React App (although the specific technology is not crucial to this discussion), I have encountered a situation involving three asynchronous functions, which I will refer to as func1, func2, and func3. Here is a general outline ...

What steps can I take to troubleshoot and fix the height of a div/span element?

Here is my HTML code: <div> <span style="display: inline-block;height:20px">20</span> <span style="display: inline-block;"><img src="img/ex.png"/></span> </div> The image I have in the second span is sized at ...

swap between style sheets glitching

My website features two stylesheets, one for day mode and one for night mode. There is an image on the site that triggers a function with an onclick event to switch between the two stylesheets. However, when new visitors click the button for the first ti ...

Modify Bootstrap Card Styling Using JavaScript

When the clock strikes certain evening hours on my website, the Bootstrap card's default light style no longer fits the dark theme. I've attempted to switch the card to a dark style by tying in some JavaScript code, but it's not quite doing ...

Having difficulty in animating the upward movement of textbox2

I've got a form that contains 2 buttons and 2 textareas. When the form loads, I want to display only section1 (button, textarea) and the section2 button. Upon clicking the section2 button, my aim is to hide the section1 textarea, reveal the section2 t ...

Downloading a file utilizing Selenium through the window.open method

I am having trouble extracting data from a webpage that triggers a new window to open when a link is clicked, resulting in an immediate download of a csv file. The URL format is a challenge as it involves complex javascript functions called via the onClick ...