JJ_strong
JJ_strong

Reputation: 27

I don't understand why this code works this way in my code

I'm not sure what result[i] is that ? I just want to understand why this code used this way ?

function countChars(string, character) {
  var result = string;
  var count = 0;
  var i = 0;
  while ( i < string.length) {
    if (result[i] === character) {
      count = count + 1 ;
    } 

I can guess this way might work .

string[i]

Is there reason why result[i] should be in there?

function countChars(string, character) {
  var result = string;
  var count = 0;
  var i = 0;
  while ( i < string.length) {
    if (result[i] === character) {
      count = count + 1 ;
    } 
    result.slice(0,1);
    i++
  }
  return count;
}

console.log(
  countChars("hello","h") // >> 1
)  

Upvotes: 0

Views: 67

Answers (2)

mplungjan
mplungjan

Reputation: 177830

It is taking a copy so the original string is not modified in a possibly destructive code - in your code the result.slice does not modify result so the code is actually not changing result and the statement is useless

Here is what is likely meant to happen

  • Take a copy
  • Slice the copy and test the first char

function countChars(string, character) {
  var copy = string;
  var count = 0;
  while (copy.length) {
    if (copy[0] === character) {
      count++;
    } 
    copy = copy.slice(1); // destructive 
  }
  console.log("String:",string,"Copy:",copy); // copy empty here
  return count;
}

console.log(
  countChars("hello","h") // >> 1
)

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386560

You could take the copy of string and remove th first character until the length is zero. Then exit the loop. No i is required, because you need only to check the first character at index zero.

function countChars(string, character) {
    var rest = string,
        count = 0;

    while (rest.length) {
        if (rest[0] === character) {
            count++;
        } 
        rest = rest.slice(1);
    }
    return count;
}

console.log(countChars("hello", "h")); // 1

Upvotes: 0

Related Questions