简体   繁体   中英

User input JavaScript eval with variable declarations

As part of a homework I am trying to implement a JavaScript console similar to the one available in Firebug in a browser environment. From what I've picked up, eval() seems to be the easiest way to do this. However, my code runs into some problems on even very basic user input. For example:

var number = 5;

Causes a syntax error rather than just evaluating to undefined like it would in Firebug. Because of this I can't seem to declare variables at all inside the eval string. If I do something more simple like:

3 + 4 * Math.PI

It works correctly. I have tried to find an example of someone using eval() on a string containing a variable declaration, and I just can't seem to find anyone doing this.

Do I need to parse the user input completely using regular expressions before compiling it into a new string for eval() ?

Can eval() understand semicolons as line breaks? I can't find people using these either.

function runMiniFirebug() {
    var userInput = document.getElementById("user-input").value;
    try {
        var userOutput = eval('(' + userInput + ')');
        document.getElementById("js-output").innerHTML += '<p class="input">>>>' + userInput + '<p>';
        document.getElementById("js-output").innerHTML += '<p class="ouput">' + userOutput + '<p>';
    }
    catch(error) {
        document.getElementById("js-output").innerHTML += '<p class="input">>>>' + userInput + '<p>';
        document.getElementById("js-output").innerHTML += '<p class="error">' + error.message + '<p>';
    }
}

EDIT: So it seems the added parens are causing the error. This is a section from my instructors slides. Is the information incorrect, or am I just interpreting it incorrectly?

Strings that are delimited with { ... }

– You have to add extra parens so that JavaScript will know that the braces are for object literals, not for delimiting statements.

• It never hurts to do this, so add parens routinely

– var test2 = "{ firstName: 'Jay', lastName: 'Sahn' }";

– var person = eval("(" + test2 + ")");

var userOutput = eval('(' + userInput + ')');

Why are you wrapping with parentheses? This creates the statement

(var number = 5;)

which is invalid syntax.

Simply remove the '(' + and + ')' .


As for your edit, that is referring to only evaluating single expressions . var number = 5; is not an expression, nor is alert(1 + 1); alert(2 + 2); alert(1 + 1); alert(2 + 2); . Wrapping either in parentheses will cause an error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM