如何将多个变量传递到“;eval”;使用“;带有“;
How to pass multiple variables into an "eval" expression using "with"?
我正试图用作用域中对象的变量来完成类似in:eval()的操作
正确的答案建议使用"with"关键字,但我找不到任何人真正使用"with"的例子。有人能解释一下如何使用"with"将多个变量传递到上面链接中的"eval"表达式中吗?
我不建议将与或eval一起使用,除非是作为一种学习练习,因为其中任何一种都会减慢代码的速度,同时使用它们尤其糟糕,更大的js社区对此表示不满。
但它确实有效:
function evalWithVariables(code) {
var scopes=[].slice.call(arguments,1), // an array of all object passed as variables
A=[], // and array of formal parameter names for our temp function
block=scopes.map(function(a,i){ // loop through the passed scope objects
var k="_"+i; // make a formal parameter name with the current position
A[i]=k; // add the formal parameter to the array of formal params
return "with("+k+"){" // return a string that call with on the new formal parameter
}).join(""), // turn all the with statements into one block to sit in front of _code_
bonus=/'breturn/.test(code) ? "": "return "; // if no return, prepend one in
// make a new function with the formal parameter list, the bonus, the orig code, and some with closers
// then apply the dynamic function to the passed data and return the result
return Function(A, block+bonus+code+Array(scopes.length+1).join("}")).apply(this, scopes);
}
evalWithVariables("a+b", {a:7}, {b:5}); // 12
evalWithVariables("(a+b*c) +' :: '+ title ", {a:7}, {b:5}, {c:10}, document);
// == "57 :: javascript - How to pass multiple variables into an "eval" expression using "with"? - Stack Overflow"
编辑为使用任意数量的作用域源,请注意属性名称冲突。再说一遍,我通常不会将与一起使用,但这有点有趣。。。
相关文章:
- 不显示带有本地json文件数据的谷歌地图脚本
- 如何创建带有插槽的vue js组件预加载程序
- 节点是否需要模块传递带有方括号的arg?这是个错误吗
- 递归使用 eval() 是检查程序执行的好方法吗?
- MeteorJS:在带有回调的vzaar api上正确使用wrapAsync
- Javascript”;类“;带有参数的扩展
- 带有加号的电话号码验证(可选)
- 创建带有和不带有JavaScript的Bootstrap下拉菜单
- 为什么忽略了eval()代码中的语法错误
- 使用D3.js计算带有字母间距的文本长度
- 使用带有JavaScript的SOAP WebService
- 下拉框,带有展开的optgroup
- 带有填充属性的SVG矩形显示在包含元素的上方插入框阴影
- 带有验证和隐藏字段值的提交按钮
- 带有行和列偏移的Javascript的Eval字符串
- 如何将多个变量传递到“;eval”;使用“;带有“;
- 如何将带有函数的javascript数据转储到eval-able字符串
- Eval在执行带有return语句的函数时总是返回错误
- 当eval带有绑定时,Nashorn找不到函数
- 带有Eval的asp按钮上的Href