lastIndexOf()

优质
小牛编辑
120浏览
2023-12-01

描述 (Description)

此方法接受子字符串并返回其在调用String对象中last出现的索引。 它还接受一个可选参数fromIndex来开始搜索,如果找不到该值,则返回-1。

语法 (Syntax)

下面给出了JavaScript的lastIndexOf()方法的语法。 我们可以使用CoffeeScript代码中的相同方法。

string.lastIndexOf(searchValue[, fromIndex])

例子 (Example)

以下示例演示了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

打开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