Javascript 数学运算的教学代码
所以我想让我的代码学习数学运算,首先我实现了calculatestr方法,它采用数字运算符NUMBER格式的字符串1+2并返回结果。首先,它应该理解+和负-。 在此之后,我需要添加方法addOperatorname,func,它向计算器教授一个新的操作。它采用运算器名称和实现它的双参数函数funca,bJavascript 数学运算的教学代码,javascript,Javascript,所以我想让我的代码学习数学运算,首先我实现了calculatestr方法,它采用数字运算符NUMBER格式的字符串1+2并返回结果。首先,它应该理解+和负-。 在此之后,我需要添加方法addOperatorname,func,它向计算器教授一个新的操作。它采用运算器名称和实现它的双参数函数funca,b function Calculator(){ this.calculate = function(str){ this.str = str; le
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)
当我尝试添加**操作时,我没有定义,我不知道如何让它学习它。我完全重新排列了代码,所以看起来像这样
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
我创建了一个对象操作,有+键和-键,分别有函数值,函数值分别执行操作,之后我更改了整个构造函数计算器,这样它就可以识别用户的输入,然后根据用户想要的操作,我检查对象的键,如果它匹配这个函数,就会返回想要的函数。
最后,我修改了addOperator函数,它将给定的键和值添加到对象操作中,因此它学习了新的操作。现在+和-运算符在计算函数中硬编码,addOperator什么也不做。你期待什么?而AddOperator似乎什么都不做。它覆盖了name和func,但它们从未被使用过。它也完全忽略了它的func参数。我只需要一些关于重新排列代码的建议。你应该解释一些更改以及修复原始问题的方法。你的问题是什么?我自己算出了答案,所以我没有问题了。