CoffeeScript 字串 - indexOf()



說明

此方法接受一個子字串並返回其在呼叫字串物件內的第一個出現位置的索引。它還接受一個可選引數 fromIndex,它將作為搜尋的起點。如果找不到值,此方法將返回 -1。

語法

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

string.indexOf(searchValue[, fromIndex])

示例

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

開啟命令提示符並如下所示編譯 .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); 

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

c:\> coffee string_indexof.coffee

在執行時,CoffeeScript 檔案會生成以下輸出。

indexOf the given string string is :8
indexOf the given string one is :15
coffeescript_strings.htm
廣告