最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - How to call and execute an operator from string? - Stack Overflow

matteradmin6PV0评论

for example:

var s = '3+3';
s.replace(/([\d.]+)([\+\-)([^,]*)/g,
        function(all, n1, operator, n2) {
                r = new Number(n1) ??? new Number(n2);
                return r;
        }
);

note: not using eval()

for example:

var s = '3+3';
s.replace(/([\d.]+)([\+\-)([^,]*)/g,
        function(all, n1, operator, n2) {
                r = new Number(n1) ??? new Number(n2);
                return r;
        }
);

note: not using eval()

Share Improve this question edited Mar 17, 2015 at 21:11 horns 1,9431 gold badge20 silver badges26 bronze badges asked Sep 9, 2011 at 0:58 The MaskThe Mask 17.5k38 gold badges115 silver badges189 bronze badges 4
  • Looks like one of the few cases where eval() would be handy. – alex Commented Sep 9, 2011 at 1:03
  • Is new Function() off limits too? – alex Commented Sep 9, 2011 at 1:07
  • Why not using eval() out of curiosity? – Demian Brecht Commented Sep 9, 2011 at 1:10
  • You might find the following series interesting: Essentials of Interpretation. They are small lesson about puter program interpretation, written in Javascript, the goal at the end IMO will be to implement a small scheme-like language. – Christian C. Salvadó Commented Sep 9, 2011 at 1:20
Add a ment  | 

3 Answers 3

Reset to default 7

Are Variable Operators Possible?

Not possible out of the box, but he gives a nice implementation to do it, as follows. Code by delnan.

var operators = {
    '+': function(a, b) { return a + b },
    '<': function(a, b) { return a < b },
     // ...
};

var op = '+';
alert(operators[op](10, 20));

So for your implementation

r = operators[operator](new Number(n1), new Number(n2));

Your regex is a bit broken.

/([\d.]+)([\+\-)([^,]*)/g

should probably be

/([\d.]+)([+-])([\d+]+)/g

then you can switch on the operator:

function (_, a, op, b) {
  switch (op) {
    case '+': return a - -b;
    case '-': return a - b;
  }
}
s.replace(/(\d+)\s*([+-])\s*(\d+)/g, function(all, s1, op, s2) {
  var n1 = Number(s1), n2 = Number(s2);
  return (op=='+') ? (n1+n2) : (n1-n2);
});
Post a comment

comment list (0)

  1. No comments so far