vendredi 22 mars 2019

Javascript: If sentence argument contains the searchValue argument, return the index at which the searchValue starts --> Error

I tried to solve the problem below:

My Index Of: Define a function, myIndexOf, that accepts three arguments:

  • source (string)
  • searchValue (string)
  • startIdx (number) - optional

If the source contains the searchValue, return the index at which the searchValue starts.

If the searchValue appears more than once in the source, return the index from the first occurance of the searchValue. If the searchValue doesn't exist in the source, return -1.

If a startIdx is passed into the function, ignore any instances of the searchValue that occur before that index. If no startIdx is provided, start searching from the beginning of the source.

Do not use the built-in .indexOf string method in your answer.

I tried the following code:

function myIndexOf(source, searchValue, startIdx=0){

  for (i=startIdx; i<=source.length - searchValue.length; i++){

    //console.log(source[i])

    let subString = source.slice(i, i+searchValue.length);

    if(subString === searchValue){
      return i
    }
    else {
      return -1
    }
  }
}

myIndexOf('twice twice', 'ice', 5);

The function should return 8 but instead it returns -1. I know the else statement is probably what's causing the error but I don't understand why the else statement can't be where it is.

Aucun commentaire:

Enregistrer un commentaire