-1

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")

4

1 に答える 1

-1

ここにスニペットがあります:

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. var を新しい ES6 仕様の const と let に置き換えました。(常に const を使用し、書き直す必要がある場合は let を使用します)
  2. シンボルがある場合、すべてのシンボルを保持するかどうかわからないので、配列を作成しました。配列を保持する代わりに、1 つのシンボルのみが必要な場合は、単一の変数を保持します。
  3. 空白のケースを追加する
于 2019-11-21T05:51:52.560 に答える