2017-04-17 110 views
1

我想要計算字符串中特定字符的數量,但得到「0」而不是正確的輸出。我知道有更簡單的方法來獲得解決方案,但我想知道如何做到這一點,以及我做錯了什麼。計算字符串中的特定字符數

function countCharacter(str, char) { 
    var count = 0; 
    for(var i = 0; i < str.length; i++){ 
    if(str.charAt(i) === char){ 
     count++; 
    } 
    return count; 
    } 
} 
countCharacter("My cat is driving my crazy", "a"); 
+2

將返回循環外 – Engineer

回答

4

特殊照顧在返回的循環,所以for循環只迭代一次:

function countCharacter(str, char) { 
    var count = 0; 
    for(var i = 0; i < str.length; i++){ 
    if(str.charAt(i) === char){ 
     count++; 
    } 
    } 
return count; 
} 
countCharacter("My cat is driving my crazy", "a"); 

順便說一句,較短:

countCharacter=(str,char)=>str.split("").reduce((count,letter)=>letter===char?count+1:count,0); 
3

返回數應在一個地方出來的迴路

1

您不小心將return聲明放入您的for循環,所以它在第一次運行循環後返回。以下修正:

function countCharacter(str, char) { 
 
    var count = 0; 
 
    for(var i = 0; i < str.length; i++){ 
 
    if(str.charAt(i) === char){ 
 
     count++; 
 
    } 
 
    } 
 
    return count; 
 
} 
 
countCharacter("My cat is driving my crazy", "a");

2

你可以嘗試splitfilter。所產生的Arraylength是發現字符數:

const aFound = "My cat is driving my crazy" 
 
    .split("")      // split per character 
 
    .filter(chr => chr === "a"); // filter on character 'a' 
 

 
const numberOfz = findCharacterInString("I'm driving my cat crazy", "z"); 
 

 
document.querySelector("pre").textContent = ` 
 
    There is/are ${aFound.length} a('s) in "My cat is driving my crazy" 
 
    There is/are ${numberOfz} z('s) in "I'm driving my cat crazy"`; 
 
    
 
// As method (case insensitive) 
 
function findCharacterInString(string2Search, character) { 
 
    return string2Search 
 
    .split("") 
 
    .filter(chr => chr.toLowerCase() === character.toLowerCase()) 
 
    .length; 
 
}
<pre></pre>