我是JS的新手,并尝试编写一个递归函数来从一个基本计算器的未知深度的JSON对象中获取运算符和数字数据。我非常接近(我认为)但是" opStack.push(obj.op)"没有在最外面的对象上工作。然而,它正在处理嵌套元素。很明显,我必须遗漏一些明显的东西,因为这看起来很简单。
因此对于测试用例' {"操作":"添加"," expr" :{" op" :"添加"," expr" :{" op" :"减去","数字" :3}}}' ; 预期的结果是我的堆栈包含{add,add,subtract,3},但它包含{add,subtract,3}
这是问题中的代码:
// function used for iterating nested objects and adding them to the stack
function iterStore(obj){
if(!(obj.number)){
opStack.push(obj.op);
iterStore(obj.expr);
}else{
opStack.push(obj.op);
opStack.push(obj.number)
return true;
}
}
这是整个代码库,包括堆栈impl:
var initial=0;
var opStack = new Stack();
// Stack implementation
function Stack(){
let items=[];
// add element to last index of array
this.push = function(value){
items.push(value);
};
// return last index of array
this.pop=function(){
return items.pop();
};
// displays but doesn't remove last index
this.peek = function(){
return items[items.length-1];
};
//checks for empty list returns boolean
this.isEmpty = function(){
return items.length==0;
};
// returns size of stack
this.size=function(){
return items.length;
};
//clears all values from stack
this.clear = function(){
console.log("Stack cleared")
items=[];
};
this.print = function(){
console.log(items);
};
}
// function used for iterating nested objects and adding them to the stack
function iterStore(obj){
if(!(obj.number)){
opStack.push(obj.op);
iterStore(obj.expr);
}else{
opStack.push(obj.op);
opStack.push(obj.number)
return true;
}
}
// function to take the data in stack and perform the operations
function operations(inStack){
var tempNum=inStack.pop();
while(inStack.length>0){
var oper=inStack.pop();
if(oper.toLowerCase()=="add"){
initial=initial+tempNum;
tempNum=intital
}else if(oper.toLowerCase()=="subtract"){
initial=initial-tempNum;
tempNum=initial;
}
}
}
// final function to call
function calc(inString){
var parsed = JSON.parse(inString);
iterStore(parsed);
operations(opStack);
console.log(initial);
}
// Test Cases
var test='{"op": "subtract", "expr" : {"op" : "add", "number" : 15}}';
var test1='{"op": "add", "expr" : {"op" : "add", "expr" : {"op" : "subtract", "number" : 3}}}' ;
var test2='{"op" : "add", "number" : 19}';