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
广告