Issue with creating a variable name inside a JavaScript for loop

Here is the code snippet I am currently working on:

var var1 = 58;

for(var i=0;i<10;i++){
 if(("var"+i) == 58) {
 console.log("they are equal");
 }
}

I am wondering why ("var" + i) is not equal to 58 in this scenario. Could someone please provide an explanation?

My understanding is that the first item is a variable while the second one is simply a string. Is there a method to have this code function as intended?

I realize this might seem like a basic question to some, but I am still at the early stages of learning to code. Any assistance would be greatly appreciated! :)

Answer №1

It is recommended to utilize an object in this scenario:

var details = {
  info1: 58
};

for(var num = 0; num < 10; num++){
 if(details["info" + num] == 58) {
   console.log("they match");
 }
}

UPDATE: @Alex proposed an alternative using window instead of details, which can be seen as a global object. This method functions in browsers, but it is worth noting that "there is no public standard that applies to the window object" (MDN).

Answer №2

let count = 58;

for(let i=0 ;i<10;i++){
    if(window["count"+i] === 58) {
         console.log("they match!");
    }
}

Answer №3

It's possible that dhilt has a more optimal answer, but you may not have the freedom to modify the other variable.

let data = 82;

for (let j = 0; j < 15; j++) {
  let current;
  try {
    current = eval('data' + j);
  } catch (e) {
    current = null;
  }
  if (current === 82) {
    console.log("they match!");
  }
}

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

Evaluate One Input Value to Determine Another Input Value

Hey there, I've made an update to the fiddle but let me clarify what I'm trying to achieve. My goal is not to implement form validation as I already have that covered with the HTML5 "required" attribute. What I'm aiming for is to customize t ...

In my Node.js/Express.js application, I have a directory that holds various images. Whenever I attempt to view these images via their URL, I encounter a 404 error message

In my Node.js/Express js project, I have the following folder structure: root ----bin ----controllers ----middleware ----models ----node_modules ----public --------images ------------test.png ----routes ----views I am currently trying to determine the cor ...

A JavaScript function that yields no value is undefined

In my AngularJS project, I have a function that makes a GET request to the backend multiple times and returns data. Here is an example of how the function is used: function getFunction(inputData) { $http.get('request URL', { params: 'so ...

Can a variable containing HTML code be iterated through with a loop?

I am currently working on setting up a select button that will receive options from an ajax call. The ajax call is functioning properly. However, I am facing a challenge when trying to create a variable containing the HTML. I am unsure of how to iterate a ...

Failure to display masonry arrangement

I am working on creating a stunning masonry layout for my webpage using some beautiful images. Take a look at the code snippet below: CSS <style> .masonryImage{float:left;} </style> JavaScript <script src="ht ...

Select a random option from the dropdown menu

I have the following script: <script> function $(id) { return document.getElementById(id); } function getImage() { $('loader').src='/misc/images/loading.gif'; var url = "http://mouse ...

The cURL command successfully executes the request, however, it fails to work in both Postman and web browsers

A problem arises when the Node Js (express) server responds to requests using cUrl, resulting in an infinite load. However, when requested via Postman or a browser, there are no errors but still faces issues. Despite searching for solutions, none of the s ...

Setting up VideoJS Flash backup

Due to Firefox's restriction on using an .mp4 file in the <video> tag, I am required to utilize the Flash fallback option on my VideoJS player. When it comes to Chrome, Safari, and IE, I can customize my VideoJS player via JavaScript to perform ...

Dealing with Large JSON Strings in ASP.NET MVC Views

Large JSON Objects (approximately 1.5 MB) are received in Controller C1. They are then converted to strings and stored in a hidden label in View V1. The JSON data in V1 is utilized by parsing it in JavaScript J1. An occurrence of Out of Memory Excepti ...

What steps do I need to take to extract the date and month from a single datepicker using the code below?

<div class="col-md-3 pull-left" style="padding:9px"> <input type="text" id="datepicker" class="form-control"> </div> The HTML and C ...

Why isn't my onScroll event triggering in my React.js application? What mistake am I making?

I am facing an issue with my onScroll event in react js. My goal is to implement infinite scrolling in react js, but unfortunately, the onScroll event is not triggering as expected. The process involves fetching posts from an API and passing them to the ...

What's preventing me from drawing a line on this D3.js chart with my Angular code?

I am attempting to create a graph on my webpage using the D3.js library for JavaScript. I am able to draw a line on an SVG using HTML, but when I try to draw a line using JavaScript, I encounter the error message: ReferenceError: d3 is not defined. Even t ...

"Ensure that all necessary fonts and assets are included in the development of your Vue component

At the moment, I am utilizing vue-cli-service build --target lib --name myLib [entry] to compile Vue into a component library for integration into other projects. Nevertheless, it only produces four files which are: dist/myLib.umd.min.js dist/myLib.umd. ...

Verify the existence of an HTML file prior to routing in AngularJS and NodeJS

Currently, I am facing a challenge in my NodeJS project that involves AngularJS for routing management. My issue lies in checking if a selected HTML file exists before routing to it. Despite trying numerous solutions, I have not been able to find one that ...

Heroku Node.js - Cross-Origin Resource Sharing (CORS) is functioning correctly for all API requests except for when using the image upload

Our web application contains numerous APIs that retrieve data from a Node.js server deployed on Heroku. Most of the APIs function correctly, with the exception of one that allows users to upload images to the server. While this API worked flawlessly in o ...

Retrieve the variable declared within the event

How can I access a variable set in an event? Here is the code snippet: $scope.$on('event_detail', function (event, args) { $scope.id = args; console.log($scope.id); // This prints the correct value }); console.log($scope.id); // ...

Using ES6 syntax, ignite the React function

Below is the code snippet provided: class Seismo extends Component { constructor(props) { super(props); this.state = { news: "" } this.updateNews = this.updateNews.bind(this) } updateNews = () => { console.log('te ...

A "Uncaught TypeError" error occurs when trying to execute a function using the dollar sign

After successfully recognizing the hover function, the console displays an error message: Uncaught TypeError: $ is not a function <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script> <script> $(docume ...

Convert a string to HTML using AngularJs

Snippet: <tr ng-repeat="x in orderCsList"> <td class="ctn"><input type="checkbox" ng-model="x.checked"></td> <td class="ctn">{{ x.wdate }}</td> <td class="text-left">{{ x.wid }}</td> <td class="te ...

Does Next js Backend support multithreading as a default feature?

As I begin my project, I am utilizing the built-in Node js server within Next js by running the next start command. However, I am uncertain as to whether it has multithreading capabilities. My inquiry is this: Would you suggest sticking with the built-in ...