开发者

Can I get the "value" of an arbitrary statement in JavaScript (like eval does, but without eval)

开发者 https://www.devze.com 2022-12-23 17:37 出处:网络
In JavaScript is there开发者_StackOverflow a way to get the \"value\" of a statement in the same way that function() { return eval(\"if (true) { 1 }\"); } returns \"1\";

In JavaScript is there开发者_StackOverflow a way to get the "value" of a statement in the same way that function() { return eval("if (true) { 1 }"); } returns "1";

function() { return if (true) { 1 } } and all similar permutations I've tried are not valid syntax.

Is eval just blessed with special powers to determine the "last" value of a statement in an expression?

Use case is a REPL that evaluates arbitrary expressions and returns the result. eval works, but I want to wrap it in function.


function(expr) { return eval(expr); }

But that really doesn't do anything more than what eval does, so I'm guessing you must want to do things with the return value of eval before returning it?

E.g.:

function custom_eval(expr) 
{
  var result = eval(expr);
  if ((typeof result))=="string")
  { 
     alert("The expression returned a string value of: " + result); 
  }
  if ((typeof result))=="number")
  {
     alert("The expression returned a number with value: " + result);
  }
  //and so on and so forth...
  return result;
 }

 var bob = custom_eval("x=\"bob\";x");
 alert(bob);

(More on the typeof operator)


To evaluate arbitrary javascript code in javascript you have three options

  • eval. This is usually considered as "dangerous", but since javascript is executed on the client's computer, they can only harm themselves (unless you provide clients with a way to share their codes).
  • Function constructor. The same concerns apply.
  • write a javascript interpreter. This is definitely tricky for "arbitrary" code.


You can use || to get the first value that isn't null/undefined/0:

var t = 1 || 'b' || 3 || 'd'; // assigns 1

var t = 0 || null || undefined || 'd'; // assigns d

You can use && to get the last value, if no short-circuiting null/undefined/0 is found first:

var t = 1 && 'b' && 3 && 'd'; // assigns d

var t = 0 && null && undefined && 'd'; // assigns 0
0

精彩评论

暂无评论...
验证码 换一张
取 消