将运算符从字符串类型转换为运算符类型 [英] Convert operator from string type to operator type

查看:257
本文介绍了将运算符从字符串类型转换为运算符类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


<233> 333 = 566

blockquote>

我的意思是第一个数字和运算符以及第二个数字随机生成。

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

  var x = parseInt(Math.random()* 1000),
y = parseInt(Math。 random()* 1000),
operators = ['+',' - ','*','/'],
operatorNum = parseInt(Math.random()* 4),
operator =操作符[operatorNum],
结果;

result = x + operator + y;

但这只是给了我一些像748/264作为一个字符串。
它不会给我生成的计算结果。



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



编辑



我正在构建Chrome扩展程序。根据Chrome扩展程序政策,我不允许使用 eval 函数。

解决方案评估它:

  result = eval(x + operator + y); 






编辑



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

  myFunctions = [
function(a,b){return a + b;},
function(a,b){return ab;},
function(a,b){return a / b;},
函数(a,b){返回a * b;}
];

然后,随机选取一个,并用x和y变量作为参数进行调用,就像您一样before: result = myFunctions [parseInt(Math.random()* 4)](x,y);


I want to generate something like this at random.

233 + 333 = 566

I mean the first number and the operator and the second number are generated at random.

So, I wrote this code now.

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;

But this just gives me something like "748/264" as a string. It doesn't give me the result of the calculation generated.

I suppose I need to convert operator from string to operator type. But, I don't think there is a operator type.

Edited

I'm building a Chrome extension. As per the Chrome extension policy, I'm not allowed to use the eval function.

解决方案

Evaluate it:

result = eval(x + operator + y);


EDIT

Since you can't use eval, you need to build your own math functions. You can just specify the four functions inside that array (if you don't actually need to know their names), like:

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;}
];

Then just randomly pick one and call it with your x and y variables as parameters, just like you did before: result = myFunctions[parseInt(Math.random()*4)](x, y);.

这篇关于将运算符从字符串类型转换为运算符类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆