Within Javascript I am having the next funtion 'myFunction'.
Note: I created the following code just for explaining my question.
var arrayReference = [1, 2];
function myFunction() {
var array = getArray();
array.forEach(function (elem) {
remove(elem.attr('id'));
});
}
function getArray() {
return arrayReference;
}
function remove(elem) {
$.each(arrayReference, function (index, el) {
if (el == element) {
arrayReference.splice(index, 1);
}
});
}
I would think that var array
is just passed by value which will not be affected by a change in arrayReference
. Yet it seems to be passed by reference. When the forEach
method is called using the fetched array, it executes the remove
method just for the first element of the array.
So to be clear: the remove
functionality is only executed once in my case. Can this have anything to do with passing by reference? I have no idea what can cause this otherwise.
Good to know: When I comment out this remove
function, the foreach is executed twice.