如何使用javascript将运算符存储在变量中

jch*_*and 4 javascript

我想在变量中存储"+"运算符.

<head>
<script type="text/javascript">
var m= function(a,b){
return a-b
}
var jj= 10 m 10;
alert(jj)
</script>
</head>
Run Code Online (Sandbox Code Playgroud)

Den*_*ret 12

避免使用eval,我建议使用功能图:

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

然后你可以使用

var key = '+';
var c = operators[key](3, 5);
Run Code Online (Sandbox Code Playgroud)

请注意,您还可以存储operators[key]在变量中.