當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


CoffeeScript String charAt()用法及代碼示例


描述

這個charAt()JavaScript 的方法返回指定索引中存在的當前字符串的字符。

字符串中的字符從左到右編入索引。第一個字符的索引為0,最後一個字符的索引比字符串的長度小1。 (stringName_length - 1 )

用法

下麵給出的是 JavaScript 的 charAt() 方法的語法。我們可以使用 CoffeeScript 代碼中的相同方法。

string.charAt(index);

它接受一個表示字符串索引的整數值,並返回指定索引處的字符。

示例

下麵的例子演示了使用charAt()CoffeeScript 代碼中的 JavaScript 方法。將此代碼保存在具有名稱的文件中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

打開command prompt並編譯 .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);

現在,打開command prompt再次運行 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 String - charAt()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。