CoffeeScript 字串 - charCodeAt()



描述

此方法返回一個數字,該數字指示指定索引處字元的 Unicode 值。

Unicode 程式碼點範圍從 0 到 1,114,111。前 128 個 Unicode 程式碼點與 ASCII 字元編碼直接匹配。charCodeAt() 始終返回小於 65,536 的值。

語法

以下是 JavaScript 中 charCodeAt() 方法的語法。我們可以在 CoffeeScript 程式碼中使用相同的方法。

string. charCodeAt(index)

它接受一個整數,表示字串的索引,並返回字串指定索引處字元的 Unicode 值。如果給定的索引不在 0 和字串長度減 1 之間,則返回NaN

示例

以下示例演示了在 CoffeeScript 程式碼中使用 JavaScript 的charCodeAt() 方法。將此程式碼儲存在名為string_charcodeat.coffee 的檔案中。

str = "This is string"

console.log "The Unicode of the character at the index (0) is:" + str.charCodeAt 0 
console.log "The Unicode of the character at the index (1) is:" + str.charCodeAt 1 
console.log "The Unicode of the character at the index (2) is:" + str.charCodeAt 2 
console.log "The Unicode of the character at the index (3) is:" + str.charCodeAt 3 
console.log "The Unicode of the character at the index (4) is:" + str.charCodeAt 4 
console.log "The Unicode of the character at the index (5) is:" + str.charCodeAt 5

開啟命令提示符並編譯 .coffee 檔案,如下所示。

c:\> coffee -c string_charcodeat.coffee

編譯後,它將為您提供以下 JavaScript 程式碼。

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

  str = "This is string";

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

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

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

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

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

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

}).call(this);

現在,再次開啟命令提示符並執行 CoffeeScript 檔案,如下所示。

c:\> coffee string_charcodeat.coffee

執行後,CoffeeScript 檔案將產生以下輸出。

The Unicode of the character at the index (0) is:84
The Unicode of the character at the index (1) is:104
The Unicode of the character at the index (2) is:105
The Unicode of the character at the index (3) is:115
The Unicode of the character at the index (4) is:32
The Unicode of the character at the index (5) is:105
coffeescript_strings.htm
廣告