So guys, I want to make a specific character counter, f.g. in word Specific we have 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
CodePudding user response:
Hi and welcome to stackoverflow!
You have two problems in your code:
- typo word.length instead of word.lenght
- word[i] instead of string[i] in the comparison
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 ;-).
CodePudding user response:
There is a typing mistake in for loop. 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"));
CodePudding user response:
You are very close to slove it! Only two mistakes: