I have a part of a debugging framework that needs to be able to run time eval objects.
Specifically, if I have a string like this "{a: 1, b:2}"
it needs to evaluate it into an object with members a
and b
with those values. However, if I do eval("{a: 1, b:2}")
it seems to evaluate it as a statement, and says something about an illegal label.
I have hacked it so that it evaluates like this:
eval("var x=" + str + "; x;");
which seems to work, but seems like a horrible hack. Any suggestions on how to do this better?
(BTW, I am aware of the dangers of eval, but this is part of a debugging framework that will not be seen by actual users.)
The eval() function evaluates JavaScript code represented as a string and returns its completion value. The source is parsed as a script.
An alternative to eval is Function() . Just like eval() , Function() takes some expression as a string for execution, except, rather than outputting the result directly, it returns an anonymous function to you that you can call. `Function() is a faster and more secure alternative to eval().
Malicious code : invoking eval can crash a computer. For example: if you use eval server-side and a mischievous user decides to use an infinite loop as their username. Terribly slow : the JavaScript language is designed to use the full gamut of JavaScript types (numbers, functions, objects, etc)… Not just strings!
page.$$eval(selector, pageFunction[, ...args])This method runs Array. from(document. querySelectorAll(selector)) within the page and passes it as the first argument to pageFunction . If pageFunction returns a Promise, then page. $$eval would wait for the promise to resolve and return its value.
You can do it using ()
to have it parse it as an object, rather than a statement, like this:
eval("(" + str + ")");
Though, you should use JSON.parse()
first, if the browser supports it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With