简体   繁体   中英

Pass a variable in an array, not a value in javascript

is there a way to pass a variable itself, not a value in javascript? I remember being able to do so in flas as3 if i remember correct which was based on javascript. I'm not sure why i can't do the same here. Your help would be much appreciated.

variable1: false,

function1() {

    this.variable1 = true //this works of course console.log(this.variable1) prints true
}

function2() {

    var temparray1 = [this.variable1]
    temparray1[0] = true //does not work like i want, it's the value in the array that change, not this.variable1

    console.log(this.variable1) //prints still false
    console.log(temparray1[0]) //prints true
}

Primitive datatypes are always passed as value, never as a reference. Javascript passes objects as references though, so you can create an object and assign the value to an attribute like so:

variable1 = {yourValue : false}
...
var temparray1 = [this.variable1]
temparray1[0].yourValue = true;

Now when accessing variable1.yourValue it should be true.

There is no way to pass a boolean by reference in Javascript, but as a workaround you can wrap your boolean in an object, like this:

var variable1 = { value: false }

function setVar() {
    variable1.value = true
}

function test() {
    var temparray1 = [variable1]
    temparray1[0].value = true
    console.log(variable1.value) // prints true
    console.log(temparray1[0].value) // also prints true
}

Javascript always passes by value. So in your case

var temparray1 = [this.variable1]

becomes

var temparray1 = [false]

So changing it does not change variable1. But if you want to change variable1 by changing the array, you should either have variable1 as an array or object. For Example:

this.variable1 = {
    value: false
}

var temparray1 = [this.variable1];
temparray1[0].value = true;

Here also, Javascript passes by value, but now this.variable1 is a reference to the object and temparray1[0] has the value of variable1, So it is also a reference to the same object.So we are changing that object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM