当前位置:优学网  >  在线题库

JavaScript中每个循环的计数

发表时间:2022-07-21 00:49:19 阅读:113

I am trying to find the total number of a specific character is in string.

for example

myString = " this is my string ";

I want to count how many "s" is in myString. I tried the following:

function myFunction(a, b) {
  const letters = b.split("");
  console.log(letters);

  letters.forEach(letter => {
    let letterCount = 0;
    if(letter === a) {
      console.log("yes")
      letterCount++;       
    }
    console.log(letterCount);      
  })
}

myFunction('s', 'this is my string') // Expected result: 3
🎖️ 优质答案
  • 过滤器是实现这一点的正确方法.

    'this is my string'.split('').filter(s => s === 's').length
    
  • 您可以使用reduce获取所有字符的信息:

    &lt!-开始代码段:js hide:false控制台:true babel:false--&gt

    &lt!-语言:lang js--&gt

    function countRepeatedChars(str) {
      return str.split('').reduce((acc, val) => {
        acc[val] = acc[val] ? ++acc[val] : 1
    
        return acc
      }, {})
    }
    
    console.log(countRepeatedChars('dfgdfghdfghdfhdfhwefw'))
    

    &lt!-结束代码段--&gt

  • Using a simple regular expression

    function escapeRegExp(string) { // from https://stackoverflow.com/a/6969486/12101554
        return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
    }
    
    const myFunction = (match, str) => str.match(new RegExp(escapeRegExp(match), "g"))?.length ?? 0;
    
    console.log(myFunction('s', 'this is my string')) // Expected result: 3
    console.log(myFunction('s', 'thi i my tring')) // Expected result: 0
    console.log(myFunction('a', 'john has five apples and six bananas')) // Expected result: 6
  • 您可以使用拆分执行以下操作:

    &lt!-开始代码段:js hide:false控制台:true babel:false--&gt

    &lt!-语言:lang js--&gt

    myString = " this is my string ";
    console.log(myString.split('s').length - 1);
    

    &lt!-结束代码段--&gt

  • 更简单的方法是使用regexp进行计数.

    &lt!-开始代码段:js hide:false控制台:true babel:false--&gt

    &lt!-语言:lang js--&gt

    myString = " Sure this iss my string ";
    console.log(myString.match(/(s)/ig).length);
    

    &lt!-结束代码段--&gt

  • 相关问题