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
coffeescript_strings.htm
廣告