0

I'm not sure why both these codes work well.

  1. if ( str.charAt(i) === char ) < this is my code
  2. if ( 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" );
Rex5
  • 771
  • 9
  • 23
JJ_strong
  • 29
  • 4
  • Here's the relevant documentation on `String` ~ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#Character_access. That should answer your question – Phil Jul 26 '19 at 04:24
  • You need to check before posting question, https://stackoverflow.com/questions/5943726/string-charatx-or-stringx – MohammadTausif Shaikh Jul 26 '19 at 04:26

1 Answers1

0

It is introduced in ES5: https://www.w3schools.com/js/js_es5.asp

ECMAScript 5 Syntactical Changes

  • Property access [ ] on strings
Ricky Mo
  • 6,285
  • 1
  • 14
  • 30