我尝试更深地循环该对象,因为该对象有树,而且非常深,为了能够使其循环并获取数据,我应该尝试递归它,我被困在这里,结果是 undefined
这是数据,输出位于其中:
function operationEvaluator(operation) {
Object.keys(operation).forEach(el => {
if(typeof operation[el] === 'object'){
return operationEvaluator(operation[el])
}
if(typeof operation[el] === 'number'){
return operation.left + operationEvaluator(operation.op)
} else {
if(operation.op == '-'){
return operation.left - operation.right.left
} else if( operation.op == '*'){
// console.log(operation.left*operation.right.left);
return operation.left * operation.right.left
} else if(operation.op == '+' ){
return operation.left + operation.right.left
} else if(operation.op == '/' ){
return operation.left / operation.right.left
}
}
})
}
var op1 = {
left: 5,
op: '-',
right: {
left: 3,
op: '*',
right: {
left: 8,
op: '-',
right: {
left: 200,
op: '/',
right: 5,
}
}
}
};
// prosses: 5 - (3 * (8 - (200 / 5)))
console.log(operationEvaluator(op1)); // 101
var op2 = {
left: {
left: 10,
op: '*',
right: {
left: 2,
op: '+',
right: 1,
},
},
op: '+',
right: {
left: 5,
op: '*',
right: {
left: 1,
op: '-',
right: {
left: 1,
op: '+',
right: 2,
}
}
}
};
// prosses: ((10 * (2 + 1)) + (5 * (1 - (1 + 2)))
console.log(operationEvaluator(op2)); // 20
我尝试console.log
最后一个条件else
中的每个数据,它显示了operation.left
和的数量>操作.右.左
但当我返回它时,结果是未定义的,没有什么可炫耀的
我错过了什么吗? else 条件的示例
IF 运算等于'*'
然后我console.log操作.left和操作.right.left
它显示了数字,我尝试将其乘以 console.log,它显示了结果,
最佳答案
您可以使用destructuring assignment在 left
、right
和 op
部分以及运算符及其函数的辅助对象中。
然后检查左
和右
操作数是否为对象,然后使用该对象递归调用函数或直接传递值。
function operationEvaluator({ left, op, right }) {
const
operators = {
'+': (a, b) => a + b,
'-': (a, b) => a - b,
'*': (a, b) => a * b,
'/': (a, b) => a / b
},
getOperand = o => typeof o === 'object'
? operationEvaluator(o)
: o;
return operators[op](getOperand(left), getOperand(right));
}
var op1 = { left: 5, op: '-', right: { left: 3, op: '*', right: { left: 8, op: '-', right: { left: 200, op: '/', right: 5 } } } },
op2 = { left: { left: 10, op: '*', right: { left: 2, op: '+', right: 1, }, }, op: '+', right: { left: 5, op: '*', right: { left: 1, op: '-', right: { left: 1, op: '+', right: 2 } } } };
// prosses: 5 - (3 * (8 - (200 / 5)))
console.log(operationEvaluator(op1)); // 101
// prosses: ((10 * (2 + 1)) + (5 * (1 - (1 + 2)))
console.log(operationEvaluator(op2)); // 20
关于javascript - 通过递归在对象中更深地循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54441195/