所以我想让我的代码学习数学运算,首先我实现了calculate(str)方法,该方法采用格式为“ NUMBER运算符NUMBER”的字符串,例如“ 1 + 2”,并返回结果。首先,它应为+和-。 之后,我需要添加方法addOperator(name,func)来教计算器一个新的操作。它带有opalator名称和实现它的两个参数的函数func(a,b)。
function Calculator(){
this.calculate = function(str){
this.str = str;
let arr = this.str.split(" ");
for (let item in arr) {
if (arr[item] == '+'){
return Number(arr[0]) + Number(arr[arr.length-1]);
}
else if (arr[item] == '-'){
return Number(arr[0]) - Number(arr[arr.length-1]);
}
}
}
this.addOperator = function (name, func){
this.name = name;
this.func = function (){};
}
}
let obj = new Calculator();
alert(obj.calculate(prompt("Enter")));
obj.addOperator("*", (a,b) => a * b);
obj.addOperator("/", (a,b) => a / b);
obj.addOperator("**", (a,b) => a ** b);
let result = obj.calculate("2 ** 3");
alert(result)
当我尝试添加未定义的“ **”操作时,我不知道如何使其学习。
答案 0 :(得分:0)
我完全重新排列了代码,所以看起来像这样
let operation = {
"+": (a,b) => a+b,
"-": (a,b) => a-b,
}
function Calculator(){
this.calculate = function(str){
this.str = str;
let arr = this.str.split(" "); // splits user's operation
let a = Number(arr[0]); // storing "number" members of an array in the variables
let b = Number(arr[2]);
for (let item in operation){ //iterating through global object
if (arr[1] == item){ // comparing the user's operation to objects key
return operation[item](a,b); // returning the function that is written in the value of objects key.
}
}
}
this.addOperator = function (name, func){
operation[name] = func; // adding the new operation to the "operation" object
}
}
let obj = new Calculator();
alert(obj.calculate(prompt("Enter")));
obj.addOperator("*", (a,b) => a * b);
obj.addOperator("/", (a,b) => a / b);
obj.addOperator("**", (a,b) => a ** b);
let result = obj.calculate("5 ** 2");
alert(result) // output is 25
我创建了一个对象操作,该对象操作具有“ +”和“-”键,分别具有执行该操作的函数值,此后,我更改了整个构造函数(“ Calculator”),以便可以识别用户的输入之后,根据用户想要执行的操作,我检查对象的键,如果与该函数匹配,则返回所需的函数。 最后,我修改了addOperator函数,该函数将赋予它的键和值添加到对象“操作”中,从而使它学会了新操作。