2016-01-09 38 views
1

我想要擴展項目的JavaScript字符串功能,我希望能夠通過函數刪除第一次出現的字符串。
JS不允許使用字符串函數的函數來更改文本。
錯誤我相信是試圖給'this'分配一個文本。
請幫助讓我知道是否有另一種方式來實現這一點。 感謝從字符串對象中刪除第一次出現的字母

// remove first occurrence of a letter from a string 
 
String.prototype.removeFirstMatch = function(char){ 
 
\t var text = ''; 
 
\t for(i = 0; i < this.length; i++){ 
 
\t \t if(this[i] == char){ 
 
\t \t \t text = this.slice(0, i) + this.slice(i + 1, this.length); 
 
\t \t } 
 
\t } 
 
\t this = text; 
 
} 
 

 
var word = 'apple'; 
 

 
word.removeFirstMatch('p'); 
 

 
console.log(word);

回答

2

在Javascript中的字符串是不可變的。這意味着你不能改變字符串對象的內容。所以,像.slice()這樣的東西實際上並沒有修改一個字符串,它會返回一個新的字符串。

所以,你的.removeFirstMatch()方法需要返回一個新的字符串,因爲它不能修改當前的字符串對象。

您也不能在Javascript中分配到this

下面是返回一個新字符串版本:

// remove first occurrence of a letter from a string 
 
String.prototype.removeFirstMatch = function(char) { 
 
    for (var i = 0; i < this.length; i++) { 
 
     if (this.charAt(i) == char) { 
 
      return this.slice(0, i) + this.slice(i + 1, this.length); 
 
     } 
 
    } 
 
    return this; 
 
} 
 

 
var word = 'apple'; 
 
var newWord = word.removeFirstMatch('p'); 
 
document.write(newWord);

注:我也把var在前面,如果i使它成爲一個局部變量,而不是一個隱含的全球性,並允許它以strict模式運行。而且,一旦找到第一場比賽,我就退出了for循環,而不是繼續循環。並且,它返回新的字符串,或者如果沒有更改,它將返回原始。


這可能被清理了一下這個:

// remove first occurrence of a letter from a string 
 
String.prototype.removeFirstMatch = function(char) { 
 
    var found = this.indexOf(char); 
 
    if (found !== -1) { 
 
     return this.slice(0, found) + this.slice(found + 1); 
 
    } 
 
    return this; 
 
} 
 

 
var word = 'apple'; 
 
var newWord = word.removeFirstMatch('p'); 
 
document.write(newWord);

0

字符串在JavaScript中是不可變的(你不能改變一個字符串...但你可以重新分配一個字符串......)

此外,您不能在一個函數中更改this的值。請參閱@ TobiasCohen的回答here

但是,你可以返回更新值,並重新分配給word返回值...

String.prototype.removeFirstMatch = function(char){ 
    var text = ''; 
    for(i = 0; i < this.length; i++){ 
    if(this[i] == char){ 
     text = this.slice(0, i) + this.slice(i + 1, this.length); 
    } 
    } 
    return text; 
} 
var word = 'apple'; 
word = word.removeFirstMatch('p'); 
console.log(word); 
0

字符串是不可變的(不能修改字符串)。但是你可以這樣做:

String.prototype.removeFirstMatch = function(char){ 
var text = ''; 
for(i = 0; i < this.length; i++){ 
    if(this[i] == char){ 
    text = this.slice(0, i) + this.slice(i + 1, this.length); 
    } 
} 
return text; 
} 
var word = 'apple'; 
newWord = word.removeFirstMatch('p'); 
console.log(newWord); 
相關問題