Answer the question
In order to leave comments, you need to log in
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
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 questionAsk a Question
731 491 924 answers to any question