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.