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


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


描述

此方法接受一個子字符串並返回其索引last在調用 String 對象中出現。它還接受一個可選參數fromIndex開始搜索時,如果未找到該值,則返回 -1。

用法

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

string.lastIndexOf(searchValue[, fromIndex])

示例

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

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

現在,打開command prompt再次運行 CoffeeScript 文件,如下所示。

c:\> coffee string_last_indexof.coffee

在執行時,CoffeeScript 文件產生以下輸出。

lastIndexOf the given string because is:46
lastIndexOf the letter a is:57

相關用法


注:本文由純淨天空篩選整理自 CoffeeScript String - lastIndexOf()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。