Coffeescript-string-charat

提供:Dev Guides
移動先:案内検索

CoffeeScript文字列-charAt()

説明

JavaScriptの* charAt()*メソッドは、指定されたインデックスに存在する現在の文字列の文字を返します。

文字列内の文字は、左から右にインデックス付けされます。 最初の文字のインデックスは0で、最後の文字のインデックスは文字列の長さよりも1つ小さくなります。 (stringName_length-1)

構文

以下に、JavaScriptのcharAt()メソッドの構文を示します。 CoffeeScriptコードから同じメソッドを使用できます。

string.charAt(index);

Stringのインデックスを表す整数値を受け入れ、指定されたインデックスの文字を返します。

次の例は、CoffeeScriptコードでJavaScriptの* charAt()メソッドを使用する方法を示しています。 このコードを *string_charat.coffee という名前のファイルに保存します

str = "This is string"

console.log "The character at the index (0) is:" + str.charAt 0
console.log "The character at the index (1) is:" + str.charAt 1
console.log "The character at the index (2) is:" + str.charAt 2
console.log "The character at the index (3) is:" + str.charAt 3
console.log "The character at the index (4) is:" + str.charAt 4
console.log "The character at the index (5) is:" + str.charAt 5
  • コマンドプロンプト*を開き、以下に示すように.coffeeファイルをコンパイルします。
c:\> coffee -c string_charat.coffee

コンパイル時に、次のJavaScriptが提供されます。

//Generated by CoffeeScript 1.10.0
(function() {
  var str;

  str = "This is string";

  console.log("The character at the index (0) is:" + str.charAt(0));

  console.log("The character at the index (1) is:" + str.charAt(1));

  console.log("The character at the index (2) is:" + str.charAt(2));

  console.log("The character at the index (3) is:" + str.charAt(3));

  console.log("The character at the index (4) is:" + str.charAt(4));

  console.log("The character at the index (5) is:" + str.charAt(5));

}).call(this);

次に、*コマンドプロンプト*を再度開き、以下に示すようにCoffeeScriptファイルを実行します。

c:\> coffee string_charat.coffee

CoffeeScriptファイルを実行すると、次の出力が生成されます。

The character at the index (0) is:T
The character at the index (1) is:h
The character at the index (2) is:i
The character at the index (3) is:s
The character at the index (4) is:
The character at the index (5) is:i