I'm trying to make a simple incrementation function for my website which will handle several different values to be incremented by different values. I want to write a global function which will let me not have to hardcode this for each value that is going to be incremented.
I got it to work when specifying the global variables manually, but for this projects I'm going to need to change many variables, so that isn't an option. Would it be possible to return the values to the global variables without having to manually specify which variables to return them to?
let minerals = 200;
let mineralTarget = document.querySelector("#minerals");
let mineralGain = 1;
function gain(target, base, gain) {
base += gain;
target.innerHTML = base;
}
window.setInterval(function(){
gain(mineralTarget, minerals, mineralGain);
console.log(minerals);
},250);
I expect the mineralTarget to increment by 1 whenever the function is called, but it is unchanged.
Javascript passes numbers by value, which means in your function you're always incrementing a copy of the original variable, without the changes being reflected back.
Arrays and objects, however, are passed by reference. If you set a property of an object, this should be able to achieve what you want. Try this:
let minerals = {
"value": 200,
"target": document.querySelector("#minerals"),
"gain": 1
}
function gain (mineral) {
mineral.value += mineral.gain;
mineral.target.innerHTML = mineral.value;
}
window.setInterval(function () {
gain(minerals);
console.log(minerals.value);
}, 250);