gpt4 book ai didi

javascript - 如何使用 "eval"将多个变量传递到 "with"表达式中?

转载 作者:行者123 更新时间:2023-12-03 11:34:51 25 4
gpt4 key购买 nike

我正在尝试完成类似的事情:eval() with variables from an object in the scope

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

最佳答案

我不建议使用witheval,除非作为学习练习,因为其中任何一个都会减慢代码速度,并且同时使用它们特别糟糕并且令人不悦由更大的 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,但这有点有趣......

关于javascript - 如何使用 "eval"将多个变量传递到 "with"表达式中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26561063/

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