Eval alternative

前端 未结 4 1622
-上瘾入骨i
-上瘾入骨i 2020-12-20 05:13

This code works as a calculator, but the scratch pad at codeacademy tells me that eval is evil. Is there another way to do the same thing without using eval?



        
4条回答
  •  时光说笑
    2020-12-20 05:22

    You can use eval safely for a simple arithmetic calculator by filtering the input- if you only accept digits, decimal points and operators (+,-,*,/) you won't get in much trouble. If you want advanced Math functions, you are better off with the parser suggestions.

    function calculate(){
        "use strict";
        var s= prompt('Enter problem');
        if(/[^0-9()*+\/ .-]+/.test(s)) throw Error('bad input...');
        try{
            var ans= eval(s);
        }
        catch(er){
            alert(er.message);
        }
        alert(ans);
    }
    
    calculate()
    

提交回复
热议问题