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

What issues are hindering the successful export of my Vue component packaged with npm?

I created a small local npm package called fomantic-ui-vue with the following main js file: import Vue from 'vue' // Import vue component import button from './elements/button/button.vue' import buttonGroup from './elements/butt ...

What could be causing axios to not function properly when used with async/await in this particular scenario

I need to update the DoorState when a button is clicked. After sending a request to the API to change the DoorState, I then call another API to check the status of the robot. Even though the DoorState has been successfully changed, it seems that the chan ...

What strategies can I use to prevent making multiple API calls inside setInterval when initializing a new connection in a socket?

I am currently working on implementing a socket system where users can request a function with an ID, and after receiving the ID, I send requests to an API every second and emit the response back to the user. Issue: Every time a new user requests the same ...

Having trouble getting anime.js to function properly in an Ionic 3 project?

I have been attempting to incorporate anime.js into my Ionic 3 project, but I keep encountering an error when using the function anime({}) in the .ts file. Error: Uncaught (in promise): TypeError: __webpack_require__.i(...) is not a function TypeError: _ ...

If you invoke revokeObjectURL, Chrome will fail to display Blob images

-----update------ After some investigation, I found that commenting out window.URL.revokeObjectURL( imgSrc ); fixed the issue in all browsers. It seems like Chrome was revoking the URL too early. I am curious to understand why this behavior occurs, and if ...

Using multiple selectors in JQuery and Javascript

I have a challenge where I need to execute different actions for specific divs. Here is the code snippet I currently have: $("#pending-cancel-1, #pending-cancel-2").click(function(){ Do something special for pending-cancel-1 and pending-cancel-2... }) ...

Is there a way to prevent the back button from functioning in my web browser?

How can I prevent the back button from being used on my webpage? Can you provide a list of possible methods to achieve this? if($data->num_rows > 0){ while($row = $data->fetch_assoc()){ header('Location:../cashier.php&apo ...

The package-lock file may vary depending on the npm version being used

I am experimenting with a new typescript react app that was created using CRA. I am running @6.4.1 on one PC and an older version on another. Interestingly, the newer version installs dependencies with an older version instead of the expected new one. ...

"ExceptionThrownByMoveTargetOutOfBounds in Selenium WebDriver for IE9 and Firefox

Having trouble with the FireFox/IE9 driver in Selenium? When using the Actions class and its moveToElement method, I keep encountering a MoveTargetOutOfBoundsException error. Despite trying different solutions like Coordinates, Point, and javascriptexecuto ...

Exploring the depths of deep populating in Mongo and Node.js

I am currently struggling with a complex data population issue. var commentSchema = mongoose.Schema({ name: String }); var userSchema = mongoose.Schema({ userId: { type: String, default: '' }, comments: [subSchema] }); var soci ...

Change the data returned by Ajax

After making an ajax request, my table gets populated with data from my array. The return is as expected, but now I want to modify this data before displaying it to the user. Whether this modification happens before or after the data is placed in the table ...

Using async/await in a POST handler within Express.js

My goal is to invoke an async function within a POST handler. The async function I'm trying to call looks like this (the code is functional): const seaport = require("./seaport.js"); // This function creates a fixed price sell order (FPSO) ...

Unleash the power of jQuery by incorporating the Ajax functionality with a hover option to enhance user interactivity. Utilize the .ajax

On my website, I have a calendar displayed with dates like "11/29/2014" stored in an attribute called "data-date". The goal is to check the server for a log file corresponding to that date and change the CSS of the div on mouse hover. Here is the current ...

Exploring the integration of React Context API within a Next.js application to streamline the authentication process

I am looking to build a react app using Next.js. However, I am currently stuck and need assistance in figuring out how to proceed. I have implemented user authentication on the backend with node.js, passport.js, passport-local-mongoose, and express.sessi ...

Error encountered during Yarn installation process: The tunneling socket was unable to be established due to a connection refusal on localhost at port 80

I have a Next.js app that needs to be built on our company servers before deployment. We use a proxy, and I've configured yarn to use the proxy as well. yarn config set proxy http://xx.xxx.xx:xxxx yarn config set httpsProxy http://xx.xxx.xx:xxxx yarn ...

What is the most effective way to send URL strings to the server-side click handler in a jQuery loop using $.each method?

As I work with URL values in my client-side script, I aim to generate links that can transmit these URL values back to my server-side click handler upon clicking. The server-side code /logclick logs the timestamp and destination of the click for auditing p ...

React: Updating a state before calling another function - Best practices

In my code, there is a state variable named list that gets updated whenever the function setList is called. The setting of the list happens within the function AddToList, where a new value is added to the existing values in the list. However, I have notice ...

Expand the scope of the javascript in your web application to cater

I am in the process of creating a web application that utilizes its own API to display content, and it is done through JavaScript using AJAX. In the past, when working with server-side processing (PHP), I used gettext for translation. However, I am now ...

Issue with template updating when utilizing ui-router and ion-tabs in Ionic framework

CODE http://codepen.io/hawkphil/pen/LEBNVB I have set up two pages (link1 and link2) accessible from a side menu. Each page contains 2 tabs: link1: tab 1.1 and tab 1.2 link2: tab 2.1 and tab 2.2 To organize the tabs, I am utilizing ion-tabs for each p ...

Connecting nodes to edges based on their unique ids in the d3.js graph library

I am encountering an issue with this code while trying to integrate it with a new JSON object called 'new_json'. Specifically, I need the links in this code to be created based on the nodes' IDs. Can anyone provide assistance with this? va ...