简体   繁体   中英

How to execute an arithmetic operation inside a string in Javascript?

I have this little example:

var myoperation = "2+2";
var myoperation2="2*5/3";
var myoperation3="3+(4/2)"

is there anyway to execute this and get a result?

Thanks a lot in advance!

You can use the eval() function. For eg: eval("2+2")

Use eval MDN: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/eval

Some people say it is evil, but it was designed for this exact purpose;

console.log(eval(myoperation)); // 4
console.log(eval(myoperation2)); // 3.33
console.log(eval(myoperation3)); // 5

You can use eval for this.

在此处输入图片说明

Don't pass any data from a remote server to eval before validating it. Damage can be done with eval .

将字符串传递给eval()函数。

你可以使用功能

var result = new Function("return " + "2+2")();

You could do this besides eval :

function run(myoperation) {
    return new Function('return ' + myoperation + ';').call();
}

run('2+2'); // return 4

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