new Function() with variable parameters

前端 未结 10 661
傲寒
傲寒 2020-12-25 11:38

I need to create a function with variable number of parameters using new Function() constructor. Something like this:

args = [\'a\', \'b\'];
bod         


        
10条回答
  •  眼角桃花
    2020-12-25 12:11

    You can do this:

    let args = '...args'
    let body = 'let [a, b] = args;return a + b'
    
    myFunc = new Function(args, body);
    console.log(myFunc(1, 2)) //3

提交回复
热议问题