How can I execute a JavaScript function from a string containing the function body and pass several parameters simultaneously?

Is there a way to call a function from a string with the body of the function? I only have the parameter names and can pass parameters to the function.

I attempted it this specific way

function callFunction(body, paramNames, params) {
  return new Function(paramNames, body)(params);
}

This solution seems to work for only one parameter. How can I modify it to handle multiple parameters?

Thank you for your help!

Answer №1

To clarify, you are looking to dynamically generate functions and pass parameters to them. This is typically achieved in two separate steps: 1 - create the function, 2 - call it.

You can find the code here

function generateFunction(body, paramNames) {
  return new Function(paramNames, body);
}

$(document).ready(function(){
    var func1 = generateFunction("return a + 1;", ["a"]);
    var func2 = generateFunction("return a + b;", ["a","b"]);
    $("#singleParam").text(func1.apply(this,[1]));
    $("#multipleParam").text(func2.apply(this, [1, 2]));
});

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

Transforming Json strings with html tags into usable html with Firebase

After spending nearly 2 hours researching, I still haven't found a simple solution to convert a JSON string containing HTML tags so that it can be displayed on a webpage without showing the tags in raw format. Even though this string <h1>Magazi ...

Adding a value to a.getAttribute in JavaScript or jQuery: A definitive guide

As a newcomer to JavaScript and jQuery, I am facing an issue with a form text field. I am attempting to append a value to it, which will then be added to Google Maps places. However, I keep getting an error message saying "a.getAttribute is not a function. ...

Retrieving Values from Array Objects - Using JavaScript

Discovering the technique to retrieve property values. Given the following: let object1 = [{name: "HappyHands31"}, {job: "website developer"}, {city: "Chicago"}]; How can I output only the value of the second object, which is "website developer"? I am ...

Creating a multimedia input field that allows users to input text, images, and gifs similar to the "Create Post" field on social media platforms like Facebook and Twitter is a

Could someone provide guidance on how to create an input field that allows for text, pictures, gifs, attachments, similar to the "Create Post" input field in Facebook, Twitter, or Quora? I would appreciate a plugin recommendation or tips on creating it m ...

Modify the SVG height using JavaScript and CSS

In my SVG file, I have paths for all the countries in the world. Each country is represented by its own individual path like this: <path inkscape:connector-curvature="0" id="PH" data-name="Philippines" data-id="PH" d="m 16 ...

Is there a way to access a component's props within the getServerSideProps() method?

Is there a way to pass parameters to a React component and then access the values of those parameters within the getServerSideProps function of the component? I am utilizing the next framework in React JS. <Menu name={menuName} /> In this example, ...

Is there a technique I could use to create a visual effect like zooming, but without altering the dimensions of the image?

I'm currently working on a project to develop a photo gallery. let img = document.createElement('img') img.src = "https://upload.wikimedia.org/wikipedia/commons/thumb/0/07/Wikipedia_logo_%28svg%29.svg/1250px-Wikipedia_logo_%28svg% ...

After attempting to implement immutable js with Redux, my state mysteriously vanished into the ether

Starting my development journey with reactjs and redux, I thought it would be beneficial to incorporate immutable.js into my workflow while using redux. However, things took a turn for the worse. Everything seemed to crash, making me wonder if I needed mo ...

The appearance of the image is distorted once it is inserted into the carousel

I am currently working on a carousel that contains 5 images with varying heights and widths. However, I am experiencing some issues with the way the images are displayed - some are stretched while others are centered within the carousel. My goal is to ens ...

The loading process in CSS can be customized using unique IDs such as loading1 and loading300

My current CSS code looks like this: #loading{ display:none; } The issue I am facing is that I need to hide multiple loading divs, each with an id that includes the word "loading". For example: <div id=loading1></div> <div id=loading42 ...

Transforming characters in a string using Javascript

Currently, I am replacing commas in a textbox. However, how do I go about replacing both a "$" and a comma if they appear together in the same line? function doValidate() { var valid = true; document.likeItemSearchForm.sup.value = document.likeItemSearc ...

Separate a tab delimited text file and store it into an array using JavaScript

Looking to parse a text file with tab-separated values in JavaScript and add them to an array? Here's how you can achieve this while excluding the header: Id Symbol 1 A 2 B 3 C 4 D 5 E 6 F 7 G This is what I have attempted so far: va ...

preventing the dropdown navigation bar from causing elements to shift to the side

I am facing an issue with my dropdown navigation bar where elements such as buttons or images get pushed to the right side when the drop-down options appear. How can I prevent this from happening? Navbar: <nav id="nav1"> ... CSS: nav#nav1 li a { ...

Changing the State of a CheckBox with ReactJS and Material UI

Utilizing Material UI's Checkbox, I am creating a form to input data and update or add values into a state object. This form serves the purpose of both editing an existing holiday or adding a new one. I'm currently facing an issue where the stat ...

Guide to generating a unique identification for a file in nodejs

Seeking help to fix issues in the code below. Any suggestions? 1- The files are not being created in the designated directory records. How can I ensure they are saved in the correct folder? 2- Involving node uuid library, how can I generate unique ids fo ...

Accordion panels refusing to collapse

I'm new to javascript and I need help with making the opened tab collapse again when the "-" sign is clicked. Here is a sample link to demonstrate: $.fn.expCollapse = function(){ $mainContainer = $(this); $mainContainer.find('.acco-he ...

Is there a way to temporarily hide content hidden with ng-hide from being displayed on the page?

Recently delving into the world of Angular, I've come across an issue where an element appears briefly on the page before disappearing. My goal is to prevent this behavior, but I am unsure how to go about it. The specific scenario involves a radio bu ...

What ways can I leverage JavaScript to convert a provided array into multiple different arrays?

I am in need of a function that meets the following criteria: Given the dimensions of an array, return all possible combination arrays based on the given numbers. The length of the given array should be equal to the length of the array returned. The size ...

Having trouble using XMLHttpRequest to pass a JavaScript variable to PHP for querying MySQL. Any solutions?

I'm attempting to retrieve data from my MySQL database by using JavaScript in my HTML file. The specific Javascript code I have is as follows: <script> function getGameNumberOfPlays() { var sentValue1 = Number; var xhttp; xhttp = ne ...

The custom Ionic slides component {Slides} will only update the reference of the last created slide component

Desired outcome: When incorporating multiple ionic slides components into a page, the ability to reference and adjust their properties based on screen size is expected. Current situation: Upon adding multiple ionic slides components to a page and attempti ...