CoffeeScript 字串 - slice()



描述

此方法接受起始結束索引值,並返回呼叫字串物件中位於給定索引值之間的部分。如果我們不傳遞結束索引值,則將字串的結尾作為結束索引值。

注意 − 我們還可以使用範圍對字串進行切片。

語法

下面給出了 JavaScript 中slice()方法的語法。我們可以在 CoffeeScript 程式碼中使用相同的方法。

string.slice( beginslice [, endSlice] )

示例

以下示例演示了在 CoffeeScript 程式碼中使用 JavaScript 的slice()方法。將此程式碼儲存在名為 string_slice.coffee 的檔案中

my_string = "Apples are round, and apples are juicy."
result = my_string.slice 3, -2
         
console.log "The required slice of the string is :: "+result

開啟命令提示符並如下所示編譯 .coffee 檔案。

c:\> coffee -c coffee string_slice.coffee

編譯時,將生成以下 JavaScript。

// Generated by CoffeeScript 1.10.0
(function() {
  var my_string, result;

  my_string = "Apples are round, and apples are juicy.";

  result = my_string.slice(3, -2);

  console.log("The required slice of the string is :: " + result);

}).call(this);

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

c:\> coffee string_slice.coffee 

執行後,CoffeeScript 檔案會產生以下輸出。

The required slice of the string is :: les are round, and apples are juic
coffeescript_strings.htm
廣告
© . All rights reserved.