gpt4 book ai didi

javascript - 使用 ExecJS 传递参数

转载 作者:数据小太阳 更新时间:2023-10-29 08:48:11 25 4
gpt4 key购买 nike

我需要在我的 Rails 4 应用程序中执行一个 javascript 函数。我用 ExecJS ( https://github.com/sstephenson/execjs ) 尝试了以下但没有成功:

my_js_function = 'function my_function(a){var b=a.split("$");var c="";for(i=0;i<=b.length-1;i++){if(!(i%2)){c+=b[i]}}var b=c.split("");c="";for(i=0;i<=b.length-1;i++){if(i%2){c+=b[i]}}return c}'
compiled_function = ExecJS.compile(my_js_function)
result = compiled_function.call(my_argument)

原始 JS 函数带有一个参数 (my_argument),我需要以某种方式将其传递给它。非常感谢任何有关如何实现这一点的帮助!

最佳答案

你很接近。你不应该使用 call,你应该这样使用 eval:

my_js_function = 'function my_function(a){var b=a.split("$");var c="";for(i=0;i<=b.length-1;i++){if(!(i%2)){c+=b[i]}}var b=c.split("");c="";for(i=0;i<=b.length-1;i++){if(i%2){c+=b[i]}}return c}'
compiled_function = ExecJS.compile(my_js_function)
compiled_function.eval('my_function("heyhey")')
#=> ehy

关于javascript - 使用 ExecJS 传递参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21109797/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com