传递数组中的变量,而不是 javascript 中的值

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

有没有办法传递变量本身,而不是 javascript 中的值?如果我记得正确的话,我记得能够在 flas as3 中这样做,这是基于 javascript。我不确定为什么我不能在这里做同样的事情。非常感谢您的帮助。

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
}

无法在 Javascript 中通过引用传递 boolean,但作为解决方法,您可以将布尔值包装在一个对象中,如下所示:

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 虽然将对象作为引用传递,因此您可以创建一个对象并将值分配给属性,如下所示:

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

现在访问variable1.yourValue应该是真的。

Javascript 总是按值传递。所以在你的情况下

var temparray1 = [this.variable1]

变成

var temparray1 = [false]

所以改变它不会改变variable1。但是,如果您想通过更改数组来更改 variable1,则应该将 variable1 作为数组或对象。例如:

this.variable1 = {
    value: false
}

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

这里也是,Javascript按值传递,但是现在this.variable1是对象的引用而temparray1[0]有variable1的值,所以也是引用同一个object.So 我们正在更改该对象。