2017-05-03 233 views
0

我目前正在爲自己進行方法練習,並遇到兩個功能有點類似的不同功能。但是,儘管兩者的第一個參數都是字符串的起始索引,但第二個參數卻讓我感到困惑並迷惑了我。本練習中substr方法和slice方法有什麼區別?

下面是我正在談論的一個例子。

var newStringMethod = 'lets try a subslice method on this string primitive data type variable'; 

這是我在本練習中爲自己創建的字符串變量。

我開始用此變量的SUBSTR方法....

var subSlice = newStringMethod.substr(7, 10); 

調用子切片後,這是返回自己的價值。

"y a subsli" 

我轉向了切片方法。

var reguarSlice = newStringMethod.slice(7, 10); 

有一次,我把它作爲一個值返回。

"y a" 

我做的,瞭解這整個事情只是簡單地計算每個單獨的字母,從0開始剛剛從使用瞭解他們清楚地表明我需要在這兩種方法的一些進一步的解釋。這兩個字符串方法的第二個參數中有哪些可區分的屬性和功能?

回答

0

你必須要知道,.slice(7, 10)方法將返回從7指數上升開始字母10指數(不包括與10th指數字母)。

var newStringMethod = 'lets try a subslice method on this string primitive data type variable'; 
 
console.log(newStringMethod.slice(7, 10));

.substr(7, 10)方法將返回字母,從7索引開始。

var newStringMethod = 'lets try a subslice method on this string primitive data type variable'; 
 
console.log(newStringMethod.substr(7, 10));

如果你正在尋找相同的結果,使用.substring函數來代替,這將返回相同的結果slice

var newStringMethod = 'lets try a subslice method on this string primitive data type variable'; 
 
console.log(newStringMethod.substring(7, 10));

0

這兩種方法的區別的屬性是:

substr將輸出從字符串中的第7個字符的下一個10個字符。這是它是做什麼的更視覺例如:

「讓TR(Y)<- 7th index一個subsl(ⅰ)在該字符串的原始數據類型變量<-10th index from 7th CE方法」

slice會簡單輸出第7個字符到第10(7 - 10)個字符(包括空格)。這是切片正在做的更直觀的例子。

讓TR(YA)<- 7th to 10th index子切片方法此字符串原始數據類型變量

0

String#substr語法:指定(length)字符的數目從

str.substr(startIndex, length) 

substr()方法返回從startIndex開始的字符串。

例如:

var newStringMethod = 'lets try a subslice method on this string primitive data type variable'; 
//       ---------- 
//       start at index 7 and return 10 characters 
var subSlice = newStringMethod.substr(7, 10); 
// returns "y a subsli" 

String#slice語法:

str.slice(beginIndex[, endIndex]) 

slice()方法提取字符串從beginIndexendIndex的部分。如果沒有指定endIndex,那麼它會從beginIndex中提取字符串部分到字符串結尾。另外請注意,結果中不包含endIndex的字符。

例如:

var newStringMethod = 'lets try a subslice method on this string primitive data type variable'; 
//       --- 
//       start at index 7 and ends at index 10 excluding value at endIndex 10 
var reguarSlice = newStringMethod.slice(7, 10); 
// returns "y a" 
相關問題