Skip to content Skip to sidebar Skip to footer

Writing Indexof Function In Javascript

I am new to JavaScript. I have created a indexof function in but it is not giving the correct output: Question is: /* Implement a function called indexOf that accepts two parameter

Solution 1:

You are making things a little harder than you need to. If you want to do this without calling the built-in indexOf(), which I assume is the point of the exercise, you just need to return from the function as soon as your condition matches. The instructions say "return the first index" — that's the i in your loop.

If you make it through the loop without finding something it's traditional to return -1:

functionindexOf(string, character) {
    let i=0;
    while(i < string.length){
        if(string[i] == character){  // yes? just return the index ireturn i
        }
        i++                          // no? increase i and move on to next loop iteration
    }
    return -1;                       // made it through the loop and without returning. This means no match was found.
}
console.log(indexOf("Mark Was Here", "M"))
console.log(indexOf("Mark Was Here", "W"))
console.log(indexOf("Mark Was Here", "X"))

Solution 2:

Assuming from your question that the exercise is to only match the first occurrence of a character and not a substring (multiple characters in a row), then the most direct way to do it is the following:

constindexOf = (word, character) => {
  for (let i = 0; i < word.length; i++) {
    if (word[i] === character) {
      return i;
    }
  }

  return -1;
}

If you also need to match substrings, leave a comment on this answer if you can't figure it out and I'll help you along.

Solution 3:

indexOf() is a built in method for strings that tells you the index of a particular character in a word. Note that this will always return the index of the FIRST matching character.-

You can write something like:

functionindexOf(string, character){
   returnstring.indexOf(character)
}

So if I were to use my function and pass in the two required arguments:

indexOf("woof", "o") //this would return 1

Post a Comment for "Writing Indexof Function In Javascript"