O
O
olya_0972018-02-16 13:04:51
JavaScript
olya_097, 2018-02-16 13:04:51

What is the str parameter in the this.calculate line, where do we call it, and why do we write 2 **3 separated by a space in the penultimate line, and not 2**3?

function Calculator() {

  var methods = {
    "-": function(a, b) {
      return a - b;
    },
    "+": function(a, b) {
      return a + b;
    }
  };

  this.calculate = function(str) {  //что значит?для чего он?

    var split = str.split(' '),
      a = +split[0],
      op = split[1],
      b = +split[2]

    if (!methods[op] || isNaN(a) || isNaN(b)) {
      return NaN;
    }

    return methods[op](a, b);
  }

  this.addMethod = function(name, func) {
    methods[name] = func;  
  };
}

var calc = new Calculator;

calc.addMethod("*", function(a, b) {
  return a * b;
});
calc.addMethod("/", function(a, b) {
  return a / b;
});
calc.addMethod("**", function(a, b) {
  return Math.pow(a, b);
});

var result = calc.calculate("2 ** 3"); //суть почему через пробел
alert( result ); // 8

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Ukolov, 2018-02-16
@alexey-m-ukolov

Because on this space, as a result, the string passed to calculate (this is str) is split into numbers and an operator:var split = str.split(' ')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question