Multiple variable evaluation in Javascript does not function properly

Currently, I have an array that I am looping through in order to create variables.

The variable names are derived from the array itself and I am using eval (only on my local machine) to achieve this. Interestingly, I can successfully create a variable and assign plain text to it. However, when attempting to set a variable within another variable, nothing happens.

In addition, I am utilizing Prototype for DOM traversal ease.

var arr_entries = some_DOM_element;

arr_entries_array = new Array();
arr_entries_array[0] = new Array();
arr_entries_array[0][0] = 'name_dd';
arr_entries_array[0][1] = arr_entries.next(13).down().next(1).innerHTML;

arr_entries_array[1] = new Array();
arr_entries_array[1][0] = 'name_pl';
arr_entries_array[1][1] = arr_entries.next(14).down().next().innerHTML;

arr_entries_array[2] = new Array();
arr_entries_array[2][0] = 'name_pm';
arr_entries_array[2][1] = arr_entries.next(15).down().next().innerHTML;

arr_entries_array[3] = new Array();
arr_entries_array[3][0] = 'name_hd';
arr_entries_array[3][1] = arr_entries.next(17).down().next().innerHTML;

arr_entries_array[4] = new Array();
arr_entries_array[4][0] = 'name_sr';
arr_entries_array[4][1] = arr_entries.next(16).down().next().innerHTML;

for(e = 0; e < arr_entries_array.length; e++)
{
    eval('var arr_entry_' + arr_entries_array[e][0] + ';');

    eval('arr_entry_' + arr_entries_array[e][0] + ' = \'' + arr_entries_array[e][1] + '\';');
}

I can successfully alert (arr_entries_array[e][1]). I can even replace it with plain text, alert the variable later, and it functions as expected.

The issue arises in the second eval line, any suggestions or insights?

Answer №1

Is it better to assign properties directly to an object?

If you're resorting to writing code within your code and then using eval() to execute it, chances are you're taking the wrong approach. This practice is inefficient, difficult to comprehend, and opens up potential security vulnerabilities.

In JavaScript, objects can accommodate any type of property. So why not simply create a new object like this:

let obj = new Object(); obj['property_name'] = value...;
, or something similar?

Answer №2

If you're encountering syntax errors inside the eval function, it could be due to the innerHTML values of certain Dom elements.

Using tools like firebug or other debugging utilities can help identify where the error is originating from in the second eval statement.

The issue might be related to new lines (\n) causing complications.

To rectify this problem, make sure to escape the values passed into eval so they are treated as literal strings within the eval statement. For example:

var text = "' quotes can be tricky"
eval("var variable = '" + text + "';"); //syntax error
eval("var variable = '" + text.replace(/'/g, "\'") + "';"); //works
var text2 = "\n new lines also";
eval("var variable = '" + text2 + "';"); //another syntax error
eval("var variable = '" + text2.replace(/\n/g, "\\n") + "';"); //works

Answer №3

In my opinion, it would be best to explore alternative approaches. While running the code solely on your personal computer may not pose security risks by exposing eval to the public, it is still considered unreliable and quite inefficient. I strongly advise against utilizing eval due to its unpredictable nature, and suggest seeking out a more efficient solution for processing.

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

Retrieve information stored in a component's data variable

After creating a Vue repository using vue init webpack my-app My main.js file looks like this -- // The Vue build version to load with the import command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue fro ...

jQuery - Enhancing User Experience with Dynamic Screen Updates

Is there a way to update the screen height when resizing or zooming the screen? Whenever I zoom the screen, the arrows break. I'm also curious if the method I'm using to display images on the screen is effective. It's supposed to be a paral ...

Choose a value to apply to the dropdown menus

I've encountered an issue with the following code - it only seems to work once and not every time: var selectedVal = $('#drpGender_0').find("option:selected").text(); if (selectedVal == "Male") { $('#drpGender_1').fi ...

The integration of Laravel (Homestead) Sanctum is malfunctioning when combined with a standalone Vue application

After running the command php artisan serve my Laravel application successfully resolves on localhost:8000. I have configured Laravel Sanctum as follows: SESSION_DRIVER=cookie SESSION_DOMAIN=localhost SANCTUM_STATEFUL_DOMAINS=localhost:8080 As for m ...

Executing MySQL queries using Ajax

Having trouble with a registration form that relies on jQuery and Ajax for validation. The issue arises when the server-side validation of the e-mail address, among other things, fails to return a result through $msg. function checkUser () { $search = ...

Utilizing jQuery to pinpoint the exact position within a Flexbox container

I have a unique setup with multiple boxes arranged using Flexbox as the container and list tags as individual boxes inside. These boxes are responsive and change position as the width is resized. My goal is to use jQuery to detect which boxes are touching ...

The element type provided is not valid: it should be a string for built-in components or a class/function for composite components. However, an object was received instead. - React Native

After conducting extensive research, I have been unable to find a solution as to why this issue persists. Can anyone shed some light on what the error might be referring to? Error: Element type is invalid: expected a string (for built-in components) or a c ...

Searching for the perfect jQuery regex to validate date formats

In my application, there is an input box that allows users to enter a string date like "today" or "tomorrow". However, I am facing a new challenge now - dates such as "3 march" or "8 january." The input box includes a dropdown menu feature where users can ...

What could be causing the consistent Mocha "timeout error" I keep encountering? Additionally, why does Node keep prompting me to resolve my promise?

I'm encountering a timeout error repeatedly, even though I have called done(). const mocha = require('mocha'); const assert = require('assert'); const Student = require('../models/student.js'); describe('CRUD Tes ...

Refresh the JavaScript graph with new data from the AJAX request

Seeking assistance in updating my javascript chart data using ajax data retrieved from a database. The specific chart being referenced is an apex chart. After submitting a form via ajax, the returned result is as follows: type: "POST",crossDomain ...

Troubleshooting AngularJS: Directive unable to access controller's variable within scope

I am facing a challenge with an element that has both a controller and a directive featuring an isolate scope: scope: { dirVar: '= ' } My objective is to execute specific parts of the directive only when a certain variable is true. I am try ...

Modifying the .textcontent attribute to showcase an image using JavaScript

I am working on a website and I want to change editButton.textContent = 'Edit'; so that it displays an image instead of text. var editButton = document.createElement('button'); editButton.textContent = 'Edit'; After exploring ...

Is there a way to customize the color of a React component from a different source?

I am currently utilizing a React component library called vertical-timeline-component-react. <Fragment> <Timeline> <Content> <ContentYear startMonth="12" monthType="t ...

Vue.js blocks the use of iframes

I've come across a peculiar issue where I need to embed an iframe inside a Vue template and then be able to modify that iframe later. The code snippet below shows the simplified version of the problem: <html> <body> <div id="app" ...

Experiencing issues with creating HTML using JavaScript?

I'm a JavaScript novice and struggling to figure out what's wrong with my code. Here is the snippet: var postCount = 0; function generatePost(title, time, text) { var div = document.createElement("div"); div.className = "content"; d ...

Bootstrap 4 tabs function perfectly in pairs, but encounter issues when there are three of them

Having trouble with bootstrap4 tabs not working properly? They function well with 2 tabs using the code below: <div class="row"> <div class="col-12"> <ul class="nav nav-tabs" id="registration-picker-acc-select" role="tablist"> ...

Limiting character count in jQuery using JSON

I am trying to manipulate the output of a snippet of code in my jQuery: <li> Speed MPH: ' + val.speed_mph + '</li>\ that is being pulled from a JSON endpoint and currently displays as: Speed MPH: 7.671862999999999 Is there a ...

Is there a way to identify if a user clicks on the scrollbar within my div element?

Is there a way to detect when someone mouses down on the scrollbar of a div element with scrollbars? ...

Progress bar status displayed while uploading multiple files

I'm currently working on a Django project where I have set up a page to input data information about a file and then upload the file itself. https://i.sstatic.net/jB5cr.png Whenever the user clicks on the 'More datasets' button, it dyna ...

What is the method for conducting an Ajax request?

Currently, I am deeply involved in a personal project to enhance my skills with Rails. The project involves developing a task management application that encompasses three primary states: todo, in progress, and done. After numerous days of trial and error, ...