首页 > 解决方案 > 在 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")

标签: javascriptarraysloopsinfix-notationprefix-notation

解决方案


这是一个片段:

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');

注意:

  1. 我用新的 ES6 规范 const 和 let 替换了 var。(始终使用 const,如果必须重写,请使用 let)
  2. 我不确定是否要保留所有符号(如果有的话),所以我做了一个数组。如果您只想要一个符号,而不是保留一个数组,只需保留一个变量
  3. 为空格添加一个额外的案例

推荐阅读