I want to pass a variable to a function and have the function change the value.
I know I can do this as an object but am wondering if there is some way to do this that I haven’t thought of.
This is what I want to do, but it doesn’t work the way I want of course:
function test1(vari) {
vari = 2;
}
var myvar1 = 1;
test1(myvar1);
console.log(myvar1);
This works, but I don’t really want to make all the variables objects:
function test2(vari) {
vari.val = 2;
}
var myvar2 = { val: 1 };
test2(myvar2);
console.log(myvar2.val);
This also works, but not an acceptable solution:
function test3(vari) {
eval(vari + ' = 2;');
}
var myvar3 = 1;
test3('myvar3');
console.log(myvar3);
Is there a better option than these?