evaluating a object string

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • jman

    evaluating a object string

    var x = eval("{ 'flag' : 1 }");
    alert(x);
    alert(x.flag);

    why doesn't the above work?


  • Henry

    #2
    Re: evaluating a object string

    On Mar 6, 12:17 pm, jman wrote:
                var x = eval("{ 'flag' : 1 }");
                alert(x);
                alert(x.flag);
    >
    why doesn't the above work?
    Because the - eval - method treats its string input as a javascript
    program and a javascript program commencing with an opening brace is a
    program that starts with a block statement. That makes the content of
    the block statement a syntax error.

    If you want to have your string interpreted as an object literal you
    have to force it into a context were it must be interpreted as an
    expression. Putting parenthesis around it will achieve that end.

    Comment

    • SAM

      #3
      Re: evaluating a object string

      Henry a écrit :
      On Mar 6, 12:17 pm, jman wrote:
      > var x = eval("{ 'flag' : 1 }");
      > alert(x);
      > alert(x.flag);
      >>
      >why doesn't the above work?
      >
      Because the - eval - method treats its string input as a javascript
      program and a javascript program commencing with an opening brace is a
      program that starts with a block statement. That makes the content of
      the block statement a syntax error.
      >
      If you want to have your string interpreted as an object literal you
      have to force it into a context were it must be interpreted as an
      expression. Putting parenthesis around it will achieve that end.
      can you give the code ?
      I didn't understand where to put these parenthesis

      Comment

      • Henry

        #4
        Re: evaluating a object string

        On Mar 6, 1:07 pm, SAM wrote:
        <snip>
        can you give the code ?
        I didn't understand where to put these parenthesis
        var x = eval("({ 'flag' : 1 })");

        - or:-

        var x = eval("("+"{ 'flag' : 1 }"+")");

        Comment

        • SAM

          #5
          Re: evaluating a object string

          Henry a écrit :
          On Mar 6, 1:07 pm, SAM wrote:
          <snip>
          >can you give the code ?
          >I didn't understand where to put these parenthesis
          >
          var x = eval("({ 'flag' : 1 })");
          Thought having tried that ... ? !

          Thanks
          now it rests to understand how that works :-)

          Perhaps there is a way to see step to step how 'eval' treats the string.

          Comment

          Working...