Is it possible to make an operator type of string into operator
<script>
var operator = $(this).val(); returns a string eg) + or -
var quantity = 5 operator 1;
</script>
currently i am using switch
It's possible, in a way, via eval, but see caveats. Example:
var result = eval("5 " + operator + " 1"); // 6 if operator is +
The problem with eval is that it's a full JavaScript evaluator, and so you have to be really sure that the content is under your control. User-contributed content, for instance, is something you have to be very, very cautious with.
Alternately, just do a switch:
switch (operator) {
case "+":
result = 5 + 1;
break;
case "-":
result = 5 - 1;
break;
case "/":
result = 5 / 1;
break;
case "*":
result = 5 * 1;
break;
// ...and so on, for your supported operators
}
The absolutely most simple way would be to use a if:
var operator = $(this).val(); // returns a string eg) + or -
var quantity;
if(operator === '-') {
quantity = 5 - 1;
} else if(operator === '+') {
quantity = 5 + 1;
}
You could also use the eval function, but eval is very rarely recommended and is not really worth it in a case like this.
No. The easiest would be to use eval:
var quantity = eval("5 " + operator + " 1");
but it is considered a bad practice. Eval is Evil. Not only do you have security concerns, it also slows down the execution of your code.
Rather, this approach is much better and safer:
var operators = {
"+": function(a, b) { return a + b; };
"-": function(a, b) { return a - b; };
};
var operatorFunction = operators[operator];
if (operatorFunction) {
var quantity = operatorFunction(5, 1);
}
var quantity = 5 operator 1;(which is incorrect), but you will be able if you have a string likevar quantity = '5 operator 1';.evalis not a good way to go. Through my years of programming I have still not encountered a single problem whereevalwould be the best answer.