简体   繁体   English

计算单个字母在一个单词中出现多少次

[英]Count how many times a single letter appears in a word

I am very new to JavaScript, and I'm trying to figure out how to count how many times a single letter appears in a word. 我是JavaScript的新手,我想弄清楚如何计算单个字母在一个单词中出现的次数。 For example, how many times does 'p' appear in 'apple' 例如, 'p'出现在'apple'多少次

Here is what I have written so far but am having trouble figuring out where am I going wrong. 这是我到目前为止所写的内容,但是在弄清楚我要去哪里出错时遇到了麻烦。

var letterInWord = function (letter, word) {
  var letter = 0;
  var word = 0;
  for (var i = 0; i < letter.charAt; i+= 1) {
    if (letter.charAt(i) === " " = true) {
        letter++;
        console.log('The letter `letter` occurs in `word` 1 time.');
    } 
  }
  return letter;
};

You've got a number of problems: 您遇到了许多问题:

  1. You're reusing parameter names as local variable names. 您正在将参数名称重新用作局部变量名称。 Use different identifiers to track each bit of information in your function. 使用不同的标识符来跟踪函数中的每条信息。
  2. letter.charAt is undefined, if letter is a number, and is a function if letter is a string. letter.charAt是不确定的,如果letter是一个数字,是一个函数,如果letter是一个字符串。 Either way, i < letter.charAt makes no sense. 无论哪种方式, i < letter.charAt都没有道理。
  3. If you're searching for letter in word why do you want to look at letter.charAt(i) ? 如果要搜索word中的letter ,为什么要查看letter.charAt(i) You probably want word.charAt(i) . 您可能需要word.charAt(i)
  4. " " = true makes no sense at all. " " = true毫无意义。

Perhaps you meant something like this? 也许您的意思是这样的?

var letterInWord = function (letter, word) {
  var count = 0;
  for (var i = 0; i < word.length; i++) {
    if (word.charAt(i) === letter) {
        count++;
    } 
  }
  return count;
};
'apple'.match(/p/g).length // outputs 2

in other words: 换一种说法:

var letterInWord = function (letter, word) {
  return (word.match( new RegExp(letter, 'g') ) || []).length;
};

FIDDLE 小提琴

Here's a smaller function that also works with characters like $ or * (and since it's calling length on a string, there's no need to use || [] ) 这是一个较小的函数,也可用于$*类的字符(并且由于它在字符串上调用length ,因此无需使用|| []

'apple'.replace(/[^p]/g,'').length // outputs 2


  
 
  
  
  
function charcount(c, str) {
  return str.replace(new RegExp('[^'+c+']','g'),'').length
}

console.log = function(x) { document.write(x + "<br />"); };
console.log( "'*' in '4*5*6' = " + charcount('*', '4*5*6') ) // outputs 2
console.log( "'p' in 'pineapples' = " + charcount('p', 'pineapples') )// outputs 3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM