Johny Johny - 22 days ago 5
Javascript Question

Return same value mutiple times in an array in Javascript

I'm trying to return a value acquired from the following function

function score(string,pattern)
{
counter=0
for(i=0;i<string.length;i++)
{
if(string.toUpperCase().substr(i,pattern.length) == pattern.toUpperCase())
counter++
}
return counter
}


into the following array

result=[]

for(i=0;i<web.length;i++){
result[result.length]=score("Coooool!","OO")
}


such that
result=4,4,4
currently,
result=4


Any help is appreciated

Answer

Issue is, when you define variables without var, they become part of global scope.

Your Code

function score(string, pattern) {
  counter = 0
  for (i = 0; i < string.length; i++) {
    if (string.toUpperCase().substr(i, pattern.length) == pattern.toUpperCase())
      counter++
  }
  return counter
}

result = []

for (i = 0; i < 4; i++) {
  console.log("Before call: ", i)
  result[result.length] = score("Coooool!", "OO")
  console.log("After call: ", i)
}

console.log(result)

Resolved Code

function score(string, pattern) {
  var counter = 0
  for (var i = 0; i < string.length; i++) {
    if (string.toUpperCase().substr(i, pattern.length) == pattern.toUpperCase())
      counter++
  }
  return counter
}

var result = []

for (var i = 0; i < 4; i++) {
  result[result.length] = score("Coooool!", "OO")
}

console.log(result)

Also as rightly pointed out by kevin kloet, you should use .push instead of result[result.length]