Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript : Pass String by value

Tags:

javascript

I have a little problem with one of my javascript code. Here is the code

//assume array is an array containing strings and myDiv, some div in my doc
for(var i in array) {
    var myString = array[i];
    var a = document.createElement('a');
    a.innerHTML = myString;
    a.addEventListener("click", function() {myFunc(myString)}, false);
    myDiv.appendChild(a)
}
function myFunc(s) {alert(s);}

However, since Strings are passed by reference in JavaScript, I see always the last string of my array when I click on the link a in question. Thus, my question is "How can I pass myString by value ?". Thank you for your help ! Phil

like image 578
user1553136 Avatar asked Feb 28 '26 20:02

user1553136


1 Answers

You should add a closure around your event handler:

JavaScript closure inside loops – simple practical example

a.addEventListener("click", function (s) {
    return function () {
        alert(s)
    };
}(myString), false);

Also, you should not use for...in loops on arrays.

like image 81
jbabey Avatar answered Mar 02 '26 08:03

jbabey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!