Alternative to eval() javascript [duplicate]

感情迁移 提交于 2019-11-27 12:44:35
Spudley

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

If your a and b variables are part of an object, you can access them with string subscripts:

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

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

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 dynamicProperty strings however you wish, so there's virtually infinite flexibility.

If your a and b variables are globals, JS globals in the browser are actually children of the window object, so you can still use this technique even with globals.

ie your global variable a could also be accessed via window.a or window['a'], with the latter option allowing you to do the same dynamicProperty trick described above.

Hope that helps.

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

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 .

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.

erdysson

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

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

can keep your res variable up to date whenever the a or b changes

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.

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

Wilt

Check more alternatives to eval in this question and another one here which both might be considered a duplicate...

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!