CoffeeScript 字串 - lastIndexOf()



說明

此方法接受一個子字串並返回其在呼叫字串物件中的最後出現時的索引。它還允許一個可選引數fromIndex從這個位置開始搜尋,如果未找到值,將返回-1。

語法

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

string.lastIndexOf(searchValue[, fromIndex])

示例

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

str1 = "A sentence does not end with because because, because is a conjunction." 
index = str1.lastIndexOf  "because"  
console.log "lastIndexOf the given string because is :" + index   
         
index = str1.lastIndexOf "a"  
console.log "lastIndexOf the letter a is :"+ index

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

c:\> coffee -c string_last_indexof.coffee

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

// Generated by CoffeeScript 1.10.0
(function() {
  var index, str1;

  str1 = "A sentence does not end with because, because because is a conjunction.";

  index = str1.lastIndexOf("because");

  console.log("lastIndexOf the given string because is :" + index);

  index = str1.lastIndexOf("a");

  console.log("lastIndexOf the letter a is :" + index);

}).call(this);

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

c:\> coffee string_last_indexof.coffee

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

lastIndexOf the given string because is :46
lastIndexOf the letter a is :57
coffeescript_strings.htm
廣告
© . All rights reserved.