JavaScript - 有多少项以某个字母开头?

时间:2016-10-07 22:21:39

标签: javascript

我有答案,有点。但最后,我只是想说,“有两个名字以字母B开头”不是我现在得到的。

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");
    }

3 个答案:

答案 0 :(得分: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 :(得分: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")
);

答案 2 :(得分: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>