This is a two part question.
I wrote a function to find the index of a substring inside a bigger string with the following function
function indexOf(str){
for (var x = 0; x < this.length; x++) {
if(this[x] === str) {
return x;
}
}
return -1;
};
I then set:
var string1="bbbabbaaa"
var string2="ab"
Then I called my function in this manner:
string1.indexOf(string2)
I was expecting to see -1 in the result because I was expecting the for loop to go through the characters in the string one by one and compare each letter to the string "ab". Since no single letter is equivalent to "ab", it shouldn't find a match. But what actually returned was 3, which is the index of "a". So my first question is, what happened here? how did the if(this[3] === str)
return true, isn't it basically comparing "a" with "ab", which should return false right?
if I modify my function to pass string1 in as an argument, I get the expected -1
:
function AlternativeIndexOf(str,str2){
for (var x = 0; x < str.length; x++) {
if(str[x] === str2) {
return x;
}
}
return -1;
};
calling the function this way AlternativeIndexOf(string1, string2)
, returns -1.
So my second question is, hows is calling the function AlternativeIndexOf(string1, string2)
differ from calling the function string1.indexOf(string2)