eval函数是一种动态生成代码的强大而简单的方法,那么有什么警告呢?
有没有办法做类似于以下任何一种情况:
var1 = 10; var2 = 20;
var operator = "<";
console.log(var1 operator var2); // returns true
Run Code Online (Sandbox Code Playgroud)
- 要么 -
var1 = 10; var2 = 20;
var operator = "+";
total = var1 operator var2; // total === 30
Run Code Online (Sandbox Code Playgroud) javascript variables operators dynamic-variables operator-keyword
我正在尝试将变量数学运算符插入到if语句中,这是我在解析用户提供的数学表达式时要尝试实现的示例:
maths_operator = "=="
if "test" maths_operator "test":
print "match found"
maths_operator = "!="
if "test" maths_operator "test":
print "match found"
else:
print "match not found"
Run Code Online (Sandbox Code Playgroud)
显然上面的失败了SyntaxError: invalid syntax.我已经尝试过使用exec和eval但是在if语句中都没有工作,我有什么选择来解决这个问题?
python parsing if-statement operators mathematical-expressions
据我所知eval(),由于安全性,JavaScript中的JSON对象被认为是不好的做法.如果JSON来自另一台服务器,我可以理解这种担忧.
但是如果JSON是由我自己的服务器提供的并且是使用PHP创建的json_encode(让我们假设它没有错误),那么简单地用于eval()读取JS中的JSON 是否合法,或者是否存在我目前无法想到的任何安全问题?
我真的不想处理动态加载JSON解析器,并且很乐意简单地使用eval().
PS:我显然会使用本机JSON对象,如果它可用,但想要回归到eval()IE/Opera.
作为输入验证的一种形式,我需要强制一个字符串'9>6'来评估一个布尔值.
除了评估字符串,我似乎无法找到解决方法.
我一直都听说过eval的邪恶(特别是因为我正在验证表单输入),关于它可以评估任何脚本和性能问题的事实.
但....
在我的案例中是否有任何替代方案(处理关系运算符)?
var arr = ['<9', '>2'];
var check = function (a) {
return arr.every(function (x) {
var string = '';
string += a + x;
try {
return eval(string);
} catch (e) {
return false;
}
});
};
console.log(check('3'))
Run Code Online (Sandbox Code Playgroud) 我有一个库,它具有基于某些字段过滤对象的功能(每个字段都有特定类型的类型 - 有关https://github.com/jy95/mediaScan/wiki 的更多信息)
最大的问题是处理来自多个来源的数字属性
// to handle number operations
export interface NumberExpressionObject {
operator: "==" | ">" | "<" | ">=" | "<=";
number: number;
}
// additional Properties
export interface AdditionalProperties {
type: AdditionalPropertiesType;
name: string;
value: boolean | string | string[] | number | NumberSearchSyntax;
}
Run Code Online (Sandbox Code Playgroud)
例如 :
expect((libInstance.filterTvSeries({
additionalProperties: [
{type: "number", name: "whateverFieldThatDoesn'tExist", value: "<50"},
{type: "number", name: "AnotherField", value: undefined},
{type: "number", name: "AnotherField2", value: "<=25"},
{type: "number", name: "AnotherField3", value: ">25"}, …Run Code Online (Sandbox Code Playgroud) 假设我们有这样的代码:
var movement = setInterval(function() {
var position = 0; // Just some example values
var limit = 200; // to go with the code below
if (position < limit) {
position = position + 10;
}
}, 500);
Run Code Online (Sandbox Code Playgroud)
是否可以用变量替换<登录position < limit和+登录position + 10(这样代码当然可以工作)?
如果是,那么最好的方法是什么?
javascript ×6
eval ×4
operators ×2
if-statement ×1
jquery ×1
json ×1
node.js ×1
parsing ×1
python ×1
security ×1
typescript ×1
variables ×1