How to pass parameters to an eval based function inJavascript

两盒软妹~` 提交于 2021-02-07 07:11:27

问题


I am storing function body in string with function name.

function fnRandom(lim){
    var data=[];
    for(var i=0;i<lim;i++)
    {
        data=data.concat(Math.floor((Math.random() * 100) + 1));
    }
return data;
}

After selecting the functionName from a drop down I use eval to execute function body.

JSON.stringify(eval(this.selectedFunction.body));

I want to pass 'lim' to this execution or can I use functionName as initiating point for execution somehow?


回答1:


Use Function constructor

var body = "console.log(arguments)"

var func = new Function( body );
func.call( null, 1, 2 ); //invoke the function using arguments

with named parameters

var body = "function( a, b ){ console.log(a, b) }"
var wrap = s => "{ return " + body + " };" //return the block having function expression
var func = new Function( wrap(body) );
func.call( null ).call( null, 1, 2  ); //invoke the function using arguments



回答2:


Eval evaluates whatever you give it to and returns even a function.

var x = eval('(y)=>y+1');
x(3) // return 4

So you can use it like this:

var lim = 3;
var body = 'return lim+1;';
JSON.stringify(eval('(lim) => {' + body + '}')(lim)); //returns "4"

Another way using Function:

var lim = 3;
JSON.stringify((new Function('lim', this.selectedFunction.body))(lim));


来源:https://stackoverflow.com/questions/49125059/how-to-pass-parameters-to-an-eval-based-function-injavascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!