Utilizing the power of combined variables in Javascript

Is there a method to incorporate variables in each loop of a javascript loop? For instance, if I were to insert this code into a loop

if (e1) {item_text += '{id:"' + id[1] + '",lvl:' + e1lvl + '},<wbr>'} 
if (e2) {item_text += '{id:"' + id[2] + '",lvl:' + e2lvl + '},<wbr>'} // and so forth

and attempt something like

for (n = 0; n < id.length; n++) { 
  if (e/*concat var e w/var n?*/) { 
    item_text += '{id:"' + id[1] + '",lvl:' + e/*concat var e w/var n?*/lvl + '},<wbr>'
  }
}

Is there a way to modify the number in the variable names (e1 -> e2 etc) during each loop iteration, or do I need to continue writing it out line by line?

Answer №1

It is technically feasible, yet strongly advised against, to utilize eval in order to generate the variable name:

const e1lvl1 = 'foo';
const e2lvl1 = 'bar';
for (let i = 1; i < 3; i++) {
  console.log(eval('e' + i + 'lvl1'));
}

However, a more preferable approach would be to enhance your script's framework so that this workaround is not required: organize each e#lvl within an array, and then retrieve the correct index from the array during each iteration:

const elvl = [
  'foo',
  'bar'
];
let item_text = '';
for (let i = 0; i < elvl.length; i++) {
  item_text += 'lvl: ' + elvl[i] + '\n';
}
console.log(item_text);

Answer №2

Make the most of arrays and objects in your JavaScript code! Instead of cluttering your code with variables like e1, e1l, e2..., consider organizing them into an object or array for easier access. Utilize JavaScript functions to ensure all elements meet specific conditions.

function submit() {
    var elements = {};
    var index = 28;
    
    for (var i = 0; i <= 24; i++) {
      elements[i] = {};
      elements[i].key = document.getElementById(`ench${i}`).checked;
      elements[i].value = $.trim(form.elements[index].value);
      
      index += 2;
    }
    
    // Check condition
    if (Object.values(elements).some(item => item.key)) {
      // At least one checked item is true
    }
    
}

Answer №3

I highly recommend updating your code to utilize arrays.

Regarding your query, given that your e1 and e1lvl variables are in the global scope, you can retrieve them using the following method:

window["e1"]
window["e1lvl"]

Feel free to experiment with this approach:

for (i = 0; i < id.length; i++) { 
  if (window["e" + i]) { 
    item_data += '{id:"' + id[i] + '",lvl:' + window["e" + i + "lvl"] + '},<wbr>';
  }
}

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

The JSON output from the gapi (Google Analytics) array in PHP is not displaying any values

I've been utilizing the gapi class within a CodeIgniter website. The implementation I'm using is based on this resource, which returns an array that functions perfectly. To pass this array to my JavaScript, I've been attempting the following ...

Save the content of the textbox on the webpage automatically, no need for a webservice or settimeout

Is there a way to save the text entered in a textbox on a webpage automatically, without relying on a webservice or the settimeout function? Any help would be greatly appreciated.Thank you in advance. ...

Having trouble implementing a transition on a dropdown menu in React

Can anyone help me troubleshoot an issue with adding a transition to a select box that appears when clicking on an input field arrow? I have tried implementing a CSS transition property, but it doesn't seem to be working. Any suggestions on what might ...

Prevent screen from loading without JavaScript using an overlay

Is there a way to darken and lock the page, preventing clicking or scrolling, while displaying white text notifying the user that JavaScript is not enabled? I understand that the recommended approach is to gracefully degrade all elements when JavaScript i ...

The innerHTML of the p tag remains unaffected when using document.getElementsById("")

HTML {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'lessons/style.css' %}" /> <script> function openNav() { document.getElementById("mySidenav").style.width = "20%"; document.getElementById("main" ...

Displaying XML data using d3js

Currently, I am working on a d3.js assignment for my school project. While looking at some examples to load an XML file, I seem to be encountering difficulties in figuring out what's going wrong. The XML file is loading correctly, but as I am still le ...

issue with angular directive not properly binding data

I am curious about the following code: HTML: <div class="overflow-hidden ag-center" world-data info="target"></div> js: .directive('worldData', ['$interval', function($interval) { return { scope: { ...

Building a personalized django widget to enhance functionality on other websites

Currently, I am in the process of developing a new website that includes user statistics. My goal is to create a widget that can be embedded on other websites using JavaScript to pull data from my server and display the statistics for a specific user. Howe ...

Initiating Internet Explorer using the APTool application for Selenium automation

Have you ever encountered a situation where you needed to open Internet Explorer from the start menu with the right-click option open with *apptool and then navigate to a specific webpage? I wonder, is it possible to automate this process using Selenium W ...

Using jQuery and AJAX manipulates the value of my variable

My AJAX request seems to be causing jQuery to change the variable that is passed to it. Here is the JavaScript code: <script type="text/javascript"> function ResolveName(id) { $.ajax({ url : 'resolvename.php', ...

Create a continuous scrolling tool similar to Google Reader for iGoogle

Do you know how to create an infinite scroll widget similar to Google Reader on iGoogle? This widget should be able to dynamically load data as the user scrolls, and replace the traditional scroll bar with a pair of up and down arrows. The HTML structure ...

Capturing and saving detailed hand-drawn artwork in high resolution

Is there a cutting-edge solution available for capturing hand-drawn sketches (from a tablet, touch screen, or iPad-like device) on a website using JavaScript and saving it on the server side? Essentially, I am looking for a mouse drawing canvas with a hig ...

Adding negative values to the Tailwind CSS utility plugin is a simple process that can greatly enhance

Adding Negative Values to Tailwind CSS Utility Plugin Quick Summary: I've developed a custom Tailwind utility plugin that includes numeric values. I'm looking for a way to introduce negative numbers by adding a - at the start of the class, simi ...

Beginner's Guide: Building your debut JavaScript/TypeScript library on GitHub and npm

I am looking to develop a simple JavaScript/TypeScript library focused on color conversion. Some of the functions and types I aim to export include: export type HEX = string; export type RGB = { r: number; g: number; b: number }; export type RGBA = { r: n ...

Utilize Javascript to perform operations on ndb.key()

When working with my application, I encounter keys that are created within a Python system and written to Google Datastore. To access the corresponding data, I require the IDs of these items, which are contained in the 'key' string. Unfortunate ...

The closing tag for the "body" element was excluded even though OMITTAG NO was specified

While attempting to validate my contact support page, I encountered the following errors: Omission of end tag for "body", even though OMITTAG NO was specified ✉ You may have forgotten to close an element or intended to self-close an element by ending ...

The specified function 'isFakeTouchstartFromScreenReader' could not be located within the '@angular/cdk/a11y' library

I encountered the following errors unexpectedly while working on my Angular 11 project: Error: ./node_modules/@angular/material/fesm2015/core.js 1091:45-77 "export 'isFakeTouchstartFromScreenReader' was not found in '@angular/cdk/a11y&a ...

Unable to access the variable field of MongoDB in JavaScript

I'm facing an issue while trying to loop through an array I retrieved from mongodb. It seems the array is treated as a single element, and here is the code snippet: const project = await Project.findOne({ embedId: inititalData.embedId }); console. ...

Passing parent props to child components in Vue.js - A comprehensive guide!

Trying to understand the process of passing a prop from parent to child components. If I include the prop attribute with the #id within the child component tag, like Image cid="488484-49544894-584854", it functions correctly. However, I am interested in u ...

Using Axios in a VUE application to handle response data

I've been working on a VUE application and I'm currently exploring how to handle post responses with Axios. Initially, I used vue-router for fetching data but decided to give Axios a try. Axios code: methods: { sendForm () { ...