[英]Circumvent operator precedence in JavaScript
Just say I have a string like this: '1 + 2 + 3 * 4' 只是说我有一个这样的字符串:'1 + 2 + 3 * 4'
Is it possible to calculate it from left to right (sequentially? Linearly?) so that it equals 24 and not 15 ? 是否可以从左到右计算它(顺序?线性?),使它等于24而不是 15?
I don't know what the string is before-hand, so it might be '1 + 2' or it might be '1 + 7 * 11 - 18 / 32 * 155' 我不知道前面的字符串是什么,所以它可能是'1 + 2'或者它可能是'1 + 7 * 11 - 18/32 * 155'
Assuming you start with a number and spaces only (and always) occur between numbers and operators, you could split the string and pass it through an object of defined operators 假设您只在数字和运算符之间出现一个数字和空格(并且始终),您可以拆分字符串并将其传递给已定义运算符的对象
var num_eval = (function () {
var ops = {
'+': function (x, y) {return x + y},
'-': function (x, y) {return x - y},
'*': function (x, y) {return x * y},
'/': function (x, y) {return x / y}
// etc..
};
return function (str_command) {
var str_arr = str_command.split(' '),
lhs = +str_arr[0], i = 1; // + to cast Number
for (; i < str_arr.length; i = i + 2) {
lhs = ops[str_arr[i]](lhs, +str_arr[i+1]); // + to cast Number
}
return lhs;
};
}());
num_eval('1 + 2 + 3 * 4'); // 24
num_eval('1 + 7 * 11 - 18 / 32 * 155'); // 339.0625
If you want to be a little more relaxed about string formatting, then you could use the following RegExp. 如果您想对字符串格式稍微放松一下,那么您可以使用以下RegExp。
str_arr = str_command.match(/([\+\-\*\/]|[\d]*[\.e]?[\d]+)/g)
The loop still assumes an odd length array, starting with a Number (as String). 循环仍假定为奇数长度数组,以Number(作为String)开头。
单行:
result = str.match(/\D*\d+/g).reduce(function(r, e) { return eval(r + e) })
Usually you just insert parenthesis. 通常你只需要插入括号。
But if by some reason you cannot do that, you can split the string by operators and then evaluate previous_part + next_part
for each of them. 但是如果由于某种原因你不能这样做,你可以通过运算符分割字符串,然后为每个字符串计算
previous_part + next_part
。
Here's a super simple example: 这是一个非常简单的例子:
var string_to_calculate = '1 + 2 + 3 * 4'
var parts = string_to_calculate.split(' ');
var result = parts[0];
for (var i = 1; i < parts.length - 1; i += 2) {
result = eval(result + parts[i] + parts[i + 1]);
}
alert(result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.