2016-10-07 46 views
0

我有答案,有點。但最後,我只想讓它說,「有兩個名字以字母B開頭」不是我現在得到的。JavaScript - 有多少項目以某個字母開頭?

var count = 0 
a = ["Bill", "Julia", "Coral", "Wendy", "Bob"]; 
for (var i = 0; i < a.length; i++) { 
    if (a[i].startsWith("B")) { 
    count++; 
    } 
    console.log("B" + " is at the beginning of " + count + " names"); 
    } 
+2

什麼是你的問題?您的控制檯日誌位於'for'循環內...... – t0mm13b

+2

縮進代碼(正確)是代碼智慧的開始。 – trincot

+0

運行時。我只是希望它輸出「B在2個名字的開頭。」現在它說:B是在1開頭的名字 B是在2開頭的名字縮進代碼?我是一個新手,這一直都沒有被覆蓋!我會去閱讀它。 –

回答

1

有兩件事情不對。首先,聲明變量計數後丟失了,。最後,你在循環內部有console.log()聲明。所以它被稱爲你想要的幾次。你必須把它放在循環的下面。

此代碼應爲你工作:

var count = 0, 
    a = ["Bill", "Julia", "Coral", "Wendy", "Bob"]; 

for (var i = 0; i < a.length; i++) { 
    if (a[i].startsWith("B")) { 
     count++; 
    } 
} 

console.log("B" + " is at the beginning of " + count + " names"); 
+1

請問downvoter,請解釋這個答案有什麼問題? (+1) – trincot

+0

是的。有用!真棒!我一直在把console.log放在裏面,我不知道它可以像這樣獨立。你的解釋總是有道理的。謝謝!!!! –

+0

@HeatherLee:如果一個答案幫助你,考慮[接受它](http://stackoverflow.com/help/someone-answers)。評論不是簡單的「謝謝,它的作品」。 – usr2564301

0
<script> 
    var count = 0,a = ["Bill", "Julia", "Coral", "Wendy", "Bob"]; 
    for (var i = 0; i < a.length; i++) { 

     //Easy way is to grab the first letter 
     if (a[i].substring(0)[0].match(/B/ig)) { 
      count=count+1; 
      console.log(a[i].substring(0)[0]+" is at the beginning of "+a[i]); 
     } 

    } 


    //TYPICALLY NOT IN THE LOOP 
    //AND NOW HERE YOU HAVE ALL THAAT MATCHED.... 
    if(count>0){ 
     //some words start with the letter B 
     //remeber to reset it @ last you u r gonna reuse it! 
    }else{ 
     //nothing matched... 
    } 

</script> 
+0

謝謝。我應該補充。我必須使用.startsWith –

+0

我們歡迎。但是,你可以讓它成爲任何你想要的東西,或許它是高度可定製的。 – Dennisrec

1

使用RegExp

const names = ["Bill", "Julia", "Coral", "Wendy", "Bob"]; 
 

 
let startsWith = (names,letter) => { 
 
    return names.filter(name => { 
 
    let pattern = new RegExp('^'+letter); 
 
    return name.match(pattern); 
 
    }); 
 
}; 
 

 
console.log( 
 
    'There are ' + startsWith(names,"B").length + ' names that start with "B"', 
 
    startsWith(names,"B") 
 
);

相關問題