简体   繁体   English

如何在Javascript中的字符串内执行算术运算?

[英]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. 您可以使用eval()函数。 For eg: eval("2+2") 例如: eval("2+2")

Use eval MDN: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/eval 使用eval MDN: https//developer.mozilla.org/zh-CN/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. 您可以为此使用eval

在此处输入图片说明

Don't pass any data from a remote server to eval before validating it. 验证之前,请勿将任何数据从远程服务器传递给eval Damage can be done with eval . 可以用eval造成损害。

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

你可以使用功能

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

You could do this besides eval : 除了eval您还可以这样做:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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