Javascript 如何将多个变量传递到;“评估”;使用“";有“吗?”;?

Javascript 如何将多个变量传递到;“评估”;使用“";有“吗?”;?,javascript,eval,Javascript,Eval,我正在努力实现以下目标: 正确答案建议使用“with”关键字,但我找不到任何人实际使用“with”的例子。有人能解释一下如何使用“with”将多个变量传递到上面链接中的“eval”表达式中吗?我不建议使用with或eval,除非作为一种学习练习,因为其中任何一个都会减慢代码的速度,同时使用它们尤其糟糕,更大的js社区不赞成 但它确实有效: function evalWithVariables(code) { var scopes=[].slice.call(arguments,1), //

我正在努力实现以下目标:


正确答案建议使用“with”关键字,但我找不到任何人实际使用“with”的例子。有人能解释一下如何使用“with”将多个变量传递到上面链接中的“eval”表达式中吗?

我不建议使用with或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"
编辑为使用任意数量的范围源,请注意属性名称冲突。
再说一遍,我通常不使用with,但这很有趣…

你说的“慢”是什么意思。使用“with”或使用“with”和“eval”?同样,您的示例只传递一个变量。如何传递多个?@John:我说的慢是指以字符串形式传递的登录比使用o1.a+o2.b之类的东西执行的慢得多。代码速度变慢的原因是查找成本更高,而eval阻止了许多编译器优化。但是,如果在运行时之前不知道变量的数量,这是行不通的。实际上,您必须从字符串动态创建函数,然后执行多次求值!正如@dandavis所说,不建议将
一起使用。原因如下-@John:edited允许任意数量的对象作为词法名称源。