本文介绍了如何在变量中加号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想计算两个数字而且非常简单。
I want to calculate two numbers and its pretty simple.
但是有没有办法在变量中运算运算符然后进行计算?
But Is there any way to take operator in variable and then do the calculation?
var x = 5;
var y = 5;
var p = '+';
var z = x + p + y;
$(".button").click(function() {
alert(z);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="button">Click ME !</div>
推荐答案
尽可能避免 eval
。对于此示例,一个简单的 switch ... case
语句就足够了:
Avoid eval
whenever possible. For this example, a simple switch...case
statement will be sufficient:
var x = 5;
var y = 5;
var z;
var p = "+";
switch (p) {
case "+":
z = x + y;
break;
case "-":
z = x - y;
break;
}
您还可以使用功能图:
You can also use a map of functions:
var fnlist = {
"+": function(a, b) { return a + b; },
"-": function(a, b) { return a - b; }
}
var x = 5;
var y = 5;
var p = "+";
var z = fnlist[p](x, y);
这篇关于如何在变量中加号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!