[英]Counting occurrences in strings and formatting strings: Displaying results
對於我的實驗室作業,練習的一部分要求我向一個已經存在的字符串中添加一個函數,該函數對字符串中特定字符出現的次數進行計數,然后返回計數。
功能如下:
var string;
var i;
var count=0;
string="Jose lived in San Jose for many years";
string.prototype.countOccurrences = function countOccurrences(thechar){
for(i = 0; i < this.length; i++){
if(this.charAt(i) == thechar){
count++;
}
}
return count;
}
我在練習中遇到的問題是顯示結果。 我正在嘗試計算並顯示字符串中字母“ e”的出現。 這就是我一直在使用的東西,但是它使程序的其余部分在運行時消失了。
document.write("There are " + string.countOccurrences("e") + "e's in this string");
有人可以指出我正確的方向嗎?
當前,您將string
作為變量。 因此,設置原型的方法將無濟於事。 您需要在String
類上進行設置。
String.prototype.countOccurrences = function( thechar ) {
var i;
var count=0;
for(i = 0; i < this.length; i++){
if(this.charAt(i) == thechar){
count++;
}
}
return count;
};
var string = "Jose lived in San Jose for many years";
document.write("There are " +string.countOccurrences("e")+ "e's in this string");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.