jQuery 替代 eval() javascript

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16037033/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 16:14:32  来源:igfitidea点击:

Alternative to eval() javascript

javascriptjqueryjquery-pluginseval

提问by Okky

I work mainly with javascript, Jquery, knockout, etc

我主要使用 javascript、Jquery、knockout 等

The thing that attracted eval() to me is

吸引我 eval() 的是

var a = 5;
var b = 10;
eval("a+b");
//Gives me output 15

Note: I work in cases where the value of aand bchanges dynamically

注意:我在a和的值b动态变化的情况下工作

In my work I'm dealing with a lot of dynamic objects from json, knockout, etc. So eval solves most of my problems. But as I read I found there are so many issues with eval() like slowing down etc.

在我的工作中,我处理了很多来自 json、knockout 等的动态对象。所以 eval 解决了我的大部分问题。但是当我阅读时,我发现 eval() 有很多问题,比如速度减慢等。

I searched a lot and haven't found any substitute for eval() when i have to evaluate equation obtaining as string into equation as object.

我搜索了很多,但没有找到任何替代 eval() 的替代品,当我必须评估作为字符串获得的方程作为对象时。

Can anyone suggest a plugin or function alternative to eval() keeping in mind the example i have given above

任何人都可以建议一个插件或函数替代 eval() 记住我上面给出的例子

Problem:

问题:

I'm creating a Table from Json data using knockout mapping. So that what ever the format of json is the table is generated. I also calculate some field using knockout computed. Right now I use hard-coded

我正在使用敲除映射从 Json 数据创建一个表。这样就生成了 json 格式的表格。我还使用计算的淘汰赛计算了一些字段。现在我使用硬编码

self.Salary = ko.computed(function(){ return self.salaryEqn() && eval(self.salaryEqn()).toFixed(2); })
self.salaryEqn(salEqnTxt); 

I want to execute these equations dynamic. I can create it dynamicaly as string but to eval them is the issue I'm facing.

我想动态地执行这些方程。我可以将它动态创建为字符串,但要评估它们是我面临的问题。

I want solution for

我想要解决方案

Is there a way to calculate a formula stored in a string in JavaScript without using eval?

有没有办法在不使用 eval 的情况下计算 JavaScript 中存储在字符串中的公式?

Like a formula

就像一个公式

 "self.Salary = ko.computed(function(){ return self.salaryEqn() && eval(self.salaryEqn()).toFixed(2); })"

采纳答案by Spudley

Javascript is a very flexible language in this regard. There are very veryfew cases where eval()is the right answer to any given question, and it certainly isn't necessary here.

在这方面,Javascript 是一种非常灵活的语言。有非常非常少数情况下eval()是正确的答案,任何给定的问题,那肯定是没有必要在这里。

If your aand bvariables are part of an object, you can access them with string subscripts:

如果您的ab变量是对象的一部分,您可以使用字符串下标访问它们:

ie myobj.acould also be referenced as myobj['a'].

iemyobj.a也可以引用为myobj['a'].

From that, you can use a variable for the subscript, and thus you can reference any element in myobjdynamically -- ie:

由此,您可以使用变量作为下标,因此您可以myobj动态引用任何元素——即:

var myobj = {a : 5, b : 10};

var dynamicProperty1 = 'a';
var dynamicProperty2 = 'b';

//gives 15.
alert( myobj[dynamicProperty1] + myobj[dynamicProperty2] );

No eval()required. You can build the dynamicPropertystrings however you wish, so there's virtually infinite flexibility.

不需要eval()。您可以随意构建dynamicProperty琴弦,因此几乎具有无限的灵活性。

If your aand bvariables are globals, JS globals in the browser are actually children of the windowobject, so you can still use this technique even with globals.

如果你的ab变量是全局变量,浏览器中的 JS 全局变量实际上是window对象的子对象,所以即使使用全局变量你仍然可以使用这种技术。

ie your global variable acould also be accessed via window.aor window['a'], with the latter option allowing you to do the same dynamicPropertytrick described above.

即您的全局变量a也可以通过window.a或访问window['a'],后一个选项允许您执行上述相同的dynamicProperty技巧。

Hope that helps.

希望有帮助。

回答by user2264587

do you mean that you want to calculate an equation that you can't know until you've received it?

你的意思是你想计算一个直到你收到它才能知道的方程吗?

if so see Calculate string value in javascript, not using eval.

如果是这样,请参阅在 javascript 中计算字符串值,而不是使用 eval

in short:

简而言之:

eval CAN be used sometimes, but only if the equation string comes from a trusted source, and there you need something like evaluating dynamic equations.

eval 有时可以使用,但前提是方程字符串来自受信任的来源,并且您需要诸如评估动态方程之类的东西。

回答by erdysson

If you can collect them under an object like root = {a: 1, b: 2}, then

如果您可以将它们收集在像 那样的对象下root = {a: 1, b: 2},那么

Object.observe(root, function(newValues) { 
    res = newValues.object.a + newValues.object.b;
});

can keep your resvariable up to date whenever the aor bchanges

可以resab更改时使您的变量保持最新

回答by Tyler

maybe using window['var' + num]might be more useful for you. i don't quite understand your question sorry.

也许使用window['var' + num]可能对你更有用。我不太明白你的问题抱歉。

回答by matchdav

It looks like you are trying to do dynamic equations created by a user.

看起来您正在尝试执行用户创建的动态方程。

For example it could be 'a+b+c' or 'dog+cat', and you don't know.

例如,它可能是“a+b+c”或“dog+cat”,而您不知道。

The best way to handle user-input equations like that is to parse the text into tokens and then translate the tokens into values/operands.

处理此类用户输入方程的最佳方法是将文本解析为标记,然后将标记转换为值/操作数。

That's a lot of work, but there are pre-rolled solutions. For example, math.js

这是很多工作,但有预卷的解决方案。例如,math.js

回答by Wilt

Check more alternatives to evalin this questionand another one herewhich both might be considered a duplicate...

检查更多的选择,以eval这一问题在这里另外一个这两个可能被视为重复...

I understand this is a link only answer, but it will for sure be helpful to others searching for alteratives to eval.

我知道这是一个仅链接的答案,但它肯定会对其他寻找eval.