I don't think this is a matter of global-local variables as the duplicate bot suggested because when I edited the wrong code and placed the counter variable inside the for loop, the same wrong output was given.
I was trying to write a function which counts the number of instances an input word/character occurs.
the test data were :
1- input (find('The quick brown fox', 'fox')) , output (“fox was found 1 times”)
2- input (find('aa, bb, cc, dd, aa', 'aa')) , output(“aa was found 2 times”)
I have attempted to solve it two times, first time the output was ”fox was found 6.333333 times ” and the second solution gave an output “fox was found 1 times”.
The difference between the two methods I attempted was the position of the final output counter and the syntax used.
first attempt:
function find(str,key){
var count = 0;
var answer = 0;
for (var i = 0; i<str.length; i++){
if (str[i] == key[0] ){
for (var j = i; j<i +str.length; j++){
if (str[j] == key[j-i]){
count = count + 1;
}
}
}
}
answer = (count)/(key.length);
return key + "was found " + answer + "times";
}
second attempt:
function find(str,key){
var count = 0;
var answer = 0;
for (var i = 0; i<str.length; i++){
if (str[i] == key[0] ){
for (var j = i; j<i +str.length; j++){
if (str[j] == key[j-i]){
count = count + 1;
}
if (count == key.length){answer = answer + 1;}
}
}
}
return key + "was found " + answer + "times";
}
I am not sure why the first one did not work, and what happened inside my code that yielded an answer of 6.3333 rather than 1?