How to access an array using a variable with the same name in JavaScript?

Possible Duplication:
Retrieve variable from string

I am facing a scenario where I have an array named myArray and a variable called myVar. The value stored in myVar is 'myArray', which happens to be the name of the array. Is there a way to refer to the elements of the array using the myVar variable? To illustrate, here is some sample code:

var myArray = {1, 2, 3};
var myVar = "myArray";

Your help is greatly appreciated!

Answer №1

Remember, the solution lies in using bracket notation.

If myArray is a global variable

var myArray  = ["1","2","3"];
var myVar = "myArray";
console.log(window[myVar]);

It's advisable to employ a namespace for better organization

var myData = {};
myData.myArray  = ["1","2","3"];
var myVar = "myArray";
console.log(myData[myVar]);

Answer №2

In the case that your array (myArray) is a global variable, you can access it using window[myVar]. However, if it is a local variable, your only option would be to utilize eval(myVar) or similar methods.

arr = window[myVar] // assuming myArray is a global variable
arr[0] = 5 // equivalent to myArray[0] = 5

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 connection between tsconfig.json and typings.json files?

I recently acquired a .NET MVC sample application that came with Angular2-final. Within the project, I noticed a typings.json file at the root and a tsconfig.json file in the ng2 app directory. What is the connection between these two files? Is this the mo ...

Importing Vue and Vuex modules from separate files

Recently, I encountered an uncommon issue. I decided to keep my main.js and store.js files separate in a Vue project. In the store.js file, I imported Vuex, set up a new vuex store, and exported it. However, when importing this file into main.js and settin ...

NextJS - The server attempted to execute the find() function, which is only available on the client side

When attempting to utilize the .find method within the server component, I encounter an error. export async function TransactionList() { const transactions = await fetch('/transactions'); return ( <ul> {transactions.m ...

Having trouble calculating the total sum within a for loop

I have a special function inside a loop that generates an array of objects. My goal is to calculate the total value returned by this function, but unfortunately I am not getting the correct sum. The function itself is working properly, however, I am unable ...

Passing no data in Angular.js ui-router.Angular.js ui-router

Within my Ionic application, there is a need to pass parameter(s) from one sub-view to another. Initially, the parameters are successfully passed as expected. However, upon returning to the first sub-view and then navigating to another sub-view, the parame ...

how to change visibility with Javascript

As I work on creating a menu using HTML and JavaScript, I've designed it to be a grid layout with 3 rows and 2 columns. The menu contents are also structured in a grid format. When the screen width is reduced, the layout changes to a single row and co ...

Is using setTimeout in a group of promises blocking in JavaScript?

Is it possible for multiple requests to be queued up and executed in sequence when calling the function func? The third promise within func includes a lengthy setTimeout that can run for as long as 3 days. Will additional calls to func trigger one after an ...

Implementing a dynamic table filter for every column using AngularJS

I have been working on a project to create a custom directive that generates a table with dynamic data and allows for sorting of columns. While the sorting function works as intended, I now want to implement filtering on all columns without specifying a sp ...

Exploring the dynamic JSON object from D3 in a Rails view

Currently, I am in the process of learning D3 and my initial attempt involves showcasing a graph where I manually hard-code the json data. To demonstrate this, I have put together a JSFiddle which you can view here: http://jsfiddle.net/Nu95q/1/ The JSFid ...

After saving any HTML, SCSS, or TS file, Angular 12 does not compile immediately

Recently I upgraded my Angular project from version 8 to 12 and then migrated to eslint. However, I have encountered an issue where the compilation does not begin immediately after saving a file. There is a delay of approximately 2 minutes before the compi ...

Showing off HTML tags within react-json-tree

I have incorporated the following npm package into my project: https://www.npmjs.com/package/react-json-tree My goal is to showcase a json tree in react, but I am facing a challenge on how to include an HTML tag as a JSON value. Are there any alternative ...

Issues Arise when Attempting to Upload Files to AWS S3 Using Node.js as

Utilizing this AWS S3 NPM Package for managing S3 uploads from my Express server has presented me with a puzzling situation. The uploader fails to trigger the end function. var key = utils.createID(Date.now()); var s3 = require('s3'); var client ...

Creating a dynamic search bar using Ajax with support for multiple keywords

I recently attempted to create an ajax search bar for my website. It functions perfectly with a single keyword, however, I'm facing some difficulty when trying to make it work with two keywords. I thought about parsing the data in the input field, but ...

Issue with React component not updating

Experiencing an issue in a React code related to nested components within React. Link to code The problem arises from having a parent component called "testing" with two child components, Component1 and Component2, each with Component3 as a sub-child und ...

Designing a personalized mat-icon using the Github SVG

Trying to create a unique custom SVG mat-icon by loading the SVG directly from Github. My initial attempt using DomSanitizer was documented in this article, and it successfully loaded the SVG via HttpClient. Now, I am attempting to achieve this directly t ...

The onchange event for the input type=file is failing to trigger on Google Chrome and Firefox

Update: Solved: http://jsfiddle.net/TmUmG/230/ Original question: I am facing an issue with handling image/logo upload alongside a hidden input type=file: <form class="image fit" id="theuploadform"> <input title="click me to chan ...

Tips for passing an additional parameter to a function within the map method in JavaScript

Is there a way to pass an additional parameter to the aggregationFunction in JavaScript when using dataArray.map(self.aggregationFunction)? I attempted using .bind(extra parameter) but it didn't yield the desired result. Any advice would be appreciate ...

Guide to pulling and showcasing information from XML at 30-second intervals using JQUERY AJAX and HTML

Seeking assistance as a beginner. Looking to retrieve and showcase data (HTML / PHP page) from XML every 30 seconds. XML FILE : <MAINData> <LiveData> <Field no="1">ENG ODI</Field> <Field no="2">ENG</Field> ...

Generate unique div elements randomly using jQuery and Javascript to populate a container

My website has a section that spans 100% width and is 450 pixels tall. This is the HTML structure... <section class="interactive-banner"> <figure></figure> </section> I am aiming for each 'figure' element to be 150 ...

Update picture using Vanilla Javascript for mobile display

I am looking to change my logo color to white when viewed on mobile devices. Currently, I have the following code for changing the logo on scroll using vanilla JavaScript. The code toggles between a dark and light logo based on the scroll position. Howev ...