javascript - 在 JavaScript 中从中缀转换为前缀表示法
问题描述
请在 JavaScript 中帮助我:我正在编写的程序是一个以前缀表示法接收表达式并以中缀表示法输出相同表达式的程序。这个程序背后的想法如下:
如果用户输入1 + 2
预期的输出是+ 1 2
. 所有有效符号都是+, -, *, /, and %
. 用户可以输入的数字数量应该是无限的(例如,如果我输入1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10
,程序应该返回+ 1 2 3 4 5 6 7 8 9 10
)。
有人可以帮我填写循环的注释部分,如果您认为有更好的方法完全解决这个问题,我愿意接受!
function infix(input) {
var x = input.split(''); // splits each variable and stores it in an array
var output = [];
var final = " "; // will be used to store our infix expression
for (var i = 0; i < x.length; i++) {
//if x[i] is any of the following : "+, -, *, /, or %" , store it in array output at index 0
//else if x[i] is a number : store it in an index of array output that is >= 1
}
for (var j = 0; j < output.length; j++) {
var final = x[0] + x[j];
}
console.log(final);
}
infix("1 + 2 + 3")
解决方案
这是一个片段:
function infix(input){
const specialCharacters = ['+', '-', '*', '/', '%'];
const allCharacters = input.split('');
const prefixes = [];
const numbers = [];
// go through all chars of input
for (let i = 0; i < allCharacters.length; i++) {
const thisCharacter = allCharacters[i];
// If the char is contained within the list of 'special chars', add it to list of prefixes.
if (specialCharacters.includes(thisCharacter))
prefixes.push(thisCharacter);
// In case this is a whit space, just do nothing and skip to next iteration
else if (thisCharacter === ' ')
continue;
// If it's a number, just add it to the array of numbers
else
numbers.push(thisCharacter);
}
// Merge both arrays
const final = [...prefixes, ...numbers];
// Back to string
const finalString = final.join(' ');
console.log(final);
console.log('String format: ' + finalString);
}
infix('1 + 2 - 3');
注意:
- 我用新的 ES6 规范 const 和 let 替换了 var。(始终使用 const,如果必须重写,请使用 let)
- 我不确定是否要保留所有符号(如果有的话),所以我做了一个数组。如果您只想要一个符号,而不是保留一个数组,只需保留一个变量
- 为空格添加一个额外的案例
推荐阅读
- django - 使用 Django 处理动态模型/数据
- c - 在我的 C 代码中需要帮助 - 获得意外的输出
- javascript - 垫子步进器不适用于选择选项
- visual-studio - 如何在运行时根据地址确定 C++ 对象的类型?
- javascript - 在 Phaser 3 TypeError 中调用 this.scene.restart(): this.body is undefined
- html - 无法获取表格单元格值
- java - 打开 url 并发送标头值
- javascript - 为什么 lodash deepClone 不对 Function 属性进行深度克隆?
- java - 使用 thymleaf 将整数中的美分值转换为 HTML 中的货币
- python - 拼字游戏:假设您正在尝试完成填字游戏