将运算符从字符串类型转换为运算符类型

crz*_*777 -1 javascript jquery google-chrome-extension

我想随机生成这样的东西.

233 + 333 = 566

我的意思是第一个数字,运算符和第二个数字是随机生成的.

所以,我现在写了这个代码.

var x = parseInt(Math.random()*1000),
    y = parseInt(Math.random()*1000),
    operators = ['+', '-', '*', '/'],
    operatorNum = parseInt(Math.random()*4),
    operator = operators[operatorNum],
    result;

result = x + operator + y;
Run Code Online (Sandbox Code Playgroud)

但这只是给我一个像"748/264"字符串的东西.它没有给我生成计算的结果.

我想我需要将运算符从字符串转换为运算符类型.但是,我认为没有运营商类型.

编辑

我正在构建Chrome扩展程序.根据Chrome扩展程序政策,我不允许使用该eval功能.

Ble*_*der 9

There are no built-in operator functions in JavaScript, but you can make your own pretty easily:

var operators = {
    '+': function(a, b) {
        return a + b;
    },
    '*': function(a, b) {
        return a * b;
    },
    ....
};
Run Code Online (Sandbox Code Playgroud)

And then call the appropriate operator:

operators['+'](4, 7);  // 11
Run Code Online (Sandbox Code Playgroud)

But here, you can just use eval and treat your string as JavaScript code:

eval('2 + 2');  // 4
Run Code Online (Sandbox Code Playgroud)


Sho*_*omz 5

评价一下:

result = eval(x + operator + y);
Run Code Online (Sandbox Code Playgroud)

编辑

由于您无法使用 eval,因此您需要构建自己的数学函数。您可以只指定该数组中的四个函数(如果您实际上不需要知道它们的名称),例如:

myFunctions = [
    function(a, b){return a+b;}, 
    function(a, b){return a-b;}, 
    function(a, b){return a/b;}, 
    function(a, b){return a*b;}
];
Run Code Online (Sandbox Code Playgroud)

然后随机选择一个并使用 x 和 y 变量作为参数调用它,就像您之前所做的那样:result = myFunctions[parseInt(Math.random()*4)](x, y);