学习数组,尝试实现对结果的后缀转换



我有以下后缀要转换:

outputArray = [3,4,*,2,9,3,/,4,/,6]

想要的结果是slicedArray = [3, * , 4 ],这样我就可以进行算术运算了。

这是我的方法,但由于某种原因而失败了。。。

let outputArray = ['3','4','*','2','9','3','/','4','/','6']
outputArray.forEach((element) => {
while ((
element !== '*' ||
element !== '+' ||
element !== '-' ||
element !== '/' ||
element !== '^'
)) {
resultArray.push(outputArray.shift(element));
console.log("Hi Panda " + resultArray)
}
if (element.includes("+") ||
element.includes("-") ||
element.includes("*") ||
element.includes("/") ||
element.includes("^")) {
let panda = resultArray.length;
resultArray.splice(panda - 1, 0, element)
let slicedArray = resultArray.slice(-3)
console.log(slicedArray);
}
})

您可以使用一个堆栈并推送所有值,直到获得一个运算符,然后添加一个带有left和reich值以及运算符的新数组。

const
operators = ['+', '-', '*', '/'],
data = [3, 4, '*', 2, 9, 3, '/', 4, '/', 6],
stack = [];

for (const value of data) {
if (operators.includes(value)) {
const
b = stack.pop(),
a = stack.pop();
stack.push([a, value, b]);
continue;
}
stack.push(value);
}
console.log(stack);
.as-console-wrapper { max-height: 100% !important; top: 0; }

获取价值的方法。

const
operators = { '+': (a, b) => a + b, '-': (a, b) => a - b, '*': (a, b) => a * b, '/': (a, b) => a / b },
data = [3, 4, '*', 2, 9, 3, '/', 4, '/', 6],
stack = [];

for (const value of data) {
if (value in operators) {
const
b = stack.pop(),
a = stack.pop();
stack.push(operators[value](a, b));
continue;
}
stack.push(value);
}
console.log(stack);
.as-console-wrapper { max-height: 100% !important; top: 0; }

最新更新