単語をアルファベット順に並べ替えるJavaScriptプログラム

Javascript

例:単語をアルファベット順に並べ替える

// program to sort words in alphabetical order

// take input
const string = prompt('Enter a sentence: ');

// converting to an array
const words = string.split(' ');

// sort the array elements
words.sort();

// display the sorted words
console.log('The sorted words are:');

for (const element of words) {
  console.log(element);
}

出力

Enter a sentence: I am learning JavaScript
The sorted words are:
I
JavaScript
am
learning

上記の例では、ユーザーは文を入力するように求められます。

  • 文は、を使用して配列要素(個々の単語)に分割されます split(' ') 方法。 ザ・ split(' ') メソッドは、文字列を空白で分割します。
    const words = string.split(' '); // ["I", "am", "learning", "JavaScript"]
  • 配列の要素は、 sort() 方法。 ザ・ sort() メソッドは、文字列をアルファベット順および昇順でソートします。
    words.sort(); // ["I", "JavaScript", "am", "learning"]
  • ザ・ for...of ループは、配列要素を反復処理して表示するために使用されます。

注意:配列値から表示する代わりに、配列要素を文字列に変換して戻し、を使用して値を文字列として表示することもできます。 join() 方法。

words.join(' '); // I JavaScript am learning



Hope this helps!

Source link

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です