0

I am using a for loop to populate an HTML table with values from an array. Each row needs a button that links to a different URL.

thisbutton.addEventListener("click", function(){ window.location.href = finalurl; });

The string finalurl changes each iteration of the loop. However it passes it as a reference, so as finalurl changes in the next loops, the event listener is still tied to it. Meaning every button on the page is then linked to this same URL.

I need a way to pass a clone inside that function, all the ways of deep copying/cloning I have found so far would require me to set a separate variable which doesn't help because this would over write as well.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

1 Answers1

0

When using for loops, especially when you're using any asynchronous code, take care to use let or const to avoid hoisting. Better yet, avoid for loops entirely, and use an Array function instead, such as forEach.

When declaring finalurl inside your for loop, do something like this:

const finalurl = '<insert url here>'

When you use var, the variable gets hoisted to the top of the function, so once the for loop finishes, there is still only one finalurl that has been reassigned multiple times, and that finalurl is the same one seen by all listeners you've attached.

Since finalurl is a primitive string, it does not get passed by reference - that's not the issue.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320