I'm not sure why both these codes work well.
if ( str.charAt(i) === char )
< this is my codeif ( str[i] === char )
<< this is others
could you tell me why str[i] works well?
Question:
Write a function called "countCharacter".
Given a string input and a character, "countCharacter" returns the number of occurrences of a given character in the given string.
Ex:
let output = countCharacter('I am a hacker', 'a');
console.log(output); // --> 3
This is mine:
function countCharacter(str, char) {
// your code here
let countRet = 0;
for ( let i = 0; i < str.length; i = i + 1 ) {
if ( str.charAt(i) === char ) { // <<< here
countRet = countRet + 1 ;
}
}
return countRet;
}
countCharacter("hello", "l" );
This is from other:
function countCharacter(str, char) {
// your code here
let countRet = 0;
for ( let i = 0; i < str.length; i = i + 1 ) {
if ( str[i] === char ) { //<<<< here
countRet = countRet + 1 ;
}
}
return countRet;
}
countCharacter("hello", "l" );