简体   繁体   English

字符串中的特定字符数

[英]Specific character count in string

So guys, I want to make a specific character counter, fg in word Specific we have 2 "i".伙计们,我想做一个特定的字符计数器,fg 在单词 Specific 中我们有 2 个“i”。 Where am I wrong?我哪里错了?

function countChar(word, char) {
  var count = 0
  for (let i = 0; i <= word.lenght; i++) {
    if (word[i] === `${char}`) {
      count += 1
    }
  }
  return count;
}
console.log(countChar("BBC","B"));
//0
//undefined

Hi and welcome to stackoverflow!您好,欢迎来到 stackoverflow!

You have two problems in your code:您的代码中有两个问题:

  • typo word.length instead of word.lenght打字错误 word.length 而不是 word.lenght
  • word[i] instead of string[i] in the comparison比较中的 word[i] 而不是 string[i]

So, your code works when you use因此,您的代码在您使用时有效

<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
function countChar(word, char) {
  var count = 0
  for (let i = 0; i <= word.length; i++) {
    if (word[i] === `${char}`) {
      count += 1
    }
  }
  return count;
}
alert (countChar("BBC","B"));
</script>
</head>
<body>
</body>
</html>

Please use a debugger, like the ones that are contained in every modern browser in the future;-).请使用调试器,就像未来每个现代浏览器中包含的调试器一样;-)。

There is a typing mistake in for loop. for 循环中存在输入错误。 Write length instead of lenght.写长度而不是长度。

Here is working code这是工作代码

function countChar(word, char) {
    var count = 0
    for (let i = 0; i <= word.length; i++) {
        if (word[i] === `${char}`) {
            count += 1
        }
    }
    return count;
}
console.log(countChar("BBC","B"));

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

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