目录

indexOf()

描述 (Description)

此方法接受子字符串并返回其在调用String对象中的first出现的索引。 它还接受一个可选参数fromIndex ,它将成为搜索的起点。 如果未找到该值,则此方法返回-1。

语法 (Syntax)

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

string.indexOf(searchValue[, fromIndex])

例子 (Example)

以下示例演示了CoffeeScript代码中JavaScript的indexOf()方法的用法。 将此代码保存在名为string_indexof.coffee的文件中

str1 = "This is string one" 
index = str1.indexOf "string" 
console.log "indexOf the given string string is :" + index 
index = str1.indexOf "one"
console.log "indexOf the given string one is :" + index 

打开command prompt并编译.coffee文件,如下所示。

c:\> coffee -c string_indexof.coffee

在编译时,它为您提供以下JavaScript。

// Generated by CoffeeScript 1.10.0
(function() {
  var index, str1;
  str1 = "This is string one";
  index = str1.indexOf("string");
  console.log("indexOf the given string string is :" + index);
  index = str1.indexOf("one");
  console.log("indexOf the given string one is :" + index);
}).call(this); 

现在,再次打开command prompt并运行CoffeeScript文件,如下所示。

c:\> coffee string_indexof.coffee

执行时,CoffeeScript文件生成以下输出。

indexOf the given string string is :8
indexOf the given string one is :15
↑回到顶部↑
WIKI教程 @2018