0

I am having a problem with my function and loop and not sure why.

var a = ['1,0,1', '0,1,0', '1,1,1'];
var b = [1, 1, 1];

function myFunction() {
  for (i = 0; i < a.length; i++) {
    var user = a[i].split(',');
    var cs = cosinesim(user, b);
    document.getElementById("cs").innerHTML += String(user) + '  ' + String(cs) + '<br>';
    cs = 0;
    user = '';
  }
}

function cosinesim(A, B) {
  var dotproduct = 0;
  var mA = 0;
  var mB = 0;
  for (i = 0; i < A.length; i++) {
    dotproduct += (parseInt(A[i]) * parseInt(B[i]));
    mA += (parseInt(A[i]) * parseInt(A[i]));
    mB += (parseInt(B[i]) * parseInt(B[i]));
  }
  mA = Math.sqrt(mA);
  mB = Math.sqrt(mB);
  if ((mA * mB) == 0) {
    var similarity = 0
  } else {
    var similarity = (dotproduct) / (mA * mB)
  }

  return similarity;
}
<p id="cs"></p>
<button onclick="myFunction()">Click</button>

I am trying to get the function to loop through the a array and print out the cosine similarity for each element in the array, however it only prints the first? If I remove the cs variable and calculations, the function prints out all the users. I am not sure why adding the cosine function within the function causes it to only run once?

Any help appreciated, thanks.

1
  • 1
    replace i = 0 with var i = 0 in your loops Commented Jul 30, 2018 at 12:52

1 Answer 1

5

You're using the same (global) variable i in both functions. You should declare i as a local variable in each:

var i;

or in the for loops:

for (var i = 0; ...

Because both loops currently use the same i, once the cosinesim() function runs, the loop in the first function will be over too.

If you code in "strict" mode, you get an error from such implicit global uses.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, did not know it would have created a global variable.
Using a let instead of a var would further improve the scoping of 'i', in case @Future expands his code.
@gkgkgkgk yes, true, though old versions of IE and the old Android browser don't support it. That's getting much less important as time goes on of course.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.