[英]How to pass object as scope to eval?
我有一個像以下javascript對象:
var myobj = {
'a': 10, 'b': 20
}
我有一個條件存儲在一個字符串中,如下所示:
var c = 'a==10';
我想評估c中的條件是真還是假。 條件字符串中引用的變量例如a
是myobj
的成員。
我嘗試了以下但它沒有幫助。
eval.call(myobj, 'a==10');
您應該真正質疑為什么要使用這樣的動態JS內容。 如果用戶提供c
的值,則需要在eval
使用之前清理該輸入。 幾乎總有更好的選擇。
因此,我現在提出的解決方案實際上是在執行一種不好的做法 - 並且在嚴格模式下不可用:
var res = eval('with (myobj) ' + c);
或者,根據您獲得有關myobj
的信息,這可能更容易/更困難:
with (myobj) var res = eval(c);
那么現在讓我們看看一些更安全的方法。 而不是使用這樣的c
值,構建一個允許的表達式結構。 例如:
var c = { prop: "a", operation: "equal", constant: 10 };
......然后做這樣的事情:
var operations = {
equal(a, b) => a == b,
// define other operations here ...
};
function test(obj, c) {
return operations[c.operation](obj[c.prop], c.constant);
}
這是我使用Function
構造函數 (在ES2015中編寫)嘗試使用這個問題的超級hacky解決方案:
const context = { a: 10, b: 20, }; const expression = 'a==10'; const getAllMatches = (pattern, string) => // make sure string is a String, and make sure pattern has the /g flag String(string).match(new RegExp(pattern, 'g')); // this pattern is far from robust const variablePattern = /[a-zA-Z$_][0-9a-zA-Z$_]*/; const evalWithContext = (context, expression) => { const variables = getAllMatches(variablePattern, expression); // function and arguments are keywords, so I use abbreviated names const func = new Function(...variables, `return (${expression})`); const args = variables.map((arg) => (Object.hasOwnProperty.call(context, arg) ? context[arg] : undefined)); return func(...args); }; console.log(evalWithContext(context, expression));
太臟了:D
var myobj = { 'a': 10, 'b': 20 } var c = 'a==10'; var res = (function() { return eval('this.' + c + ';'); }).apply(myobj); console.log(res); // or as onliner var res2 = ((o) => eval('o.' + c)).call(null, myobj); console.log(res2);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.