Reputation: 3
This Javascript function inside my class doesn't seem to modify the array that it's passed to it by reference:
this.filterEqualCities(this.birthCitiesNames, this.birthCitiesPositions);
filterEqualCities: function(citiesNames, citiesPos) {
var tempNamesArray = [];
var tempPosArray = [];
for(var i=0; i<citiesNames.length; i++) {
var name = citiesNames[i];
name = name.split(',')[0];
if(tempNamesArray.indexOf(name) == -1) {
tempNamesArray.push(name);
tempPosArray.push(citiesPos[i]);
}
}
citiesNames = [];
citiesPos = [];
for(var i=0; i<tempNamesArray.length; i++) {
citiesNames.push(tempNamesArray[i]);
citiesPos.push(tempPosArray[i]);
}
}
Upvotes: 0
Views: 69
Reputation: 18249
To expand a bit upon @Barmar's excellent answer - the issue is that arrays and other objects are not really "passed by reference" in Javascript, even though it seems that way a lot of the time, and it's often described that way. They're passed by value, like all other variables - but that "value" is itself a "reference" to an actual value stored in memory, not to another variable itself.
So if you were to modify citiesNames
, say by push
ing a new element onto it, that would be reflected outside the function - because you'd be modifying that shared value to which both citiesNames
variables (local and global) are references to.
But when you do citiesNames=[]
, you're taking the citiesNames
local variable and reassigning it to a completely new value, and there's no way your other citiesNames
variable can know about that.
This behaviour isn't unique to Javascript. Python certainly behaves the same way (and perhaps others too that I'm not as familiar with).
Upvotes: 0
Reputation: 781096
When you do:
citiesNames = [];
citiesPos = [];
the variables are no longer references to the original arrays that were passed in, now they're references to these two empty arrays.
If you want to clear out the original arrays, you can simply set their lengths:
citiesNames.length = 0;
citiesPos.length = 0;
Upvotes: 1