简体   繁体   English

在数组中传递变量,而不是在JavaScript中传递值

[英]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? 有没有办法传递变量本身,而不是JavaScript中的值? I remember being able to do so in flas as3 if i remember correct which was based on javascript. 我记得能够在flas as3中做到这一点,如果我记得是基于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: 尽管Javascript会将对象作为引用传递,所以您可以创建一个对象并将值分配给属性,如下所示:

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

Now when accessing variable1.yourValue it should be true. 现在,当访问variable1.yourValue时,它应该为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: 没有办法在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 always passes by value. Javascript总是按值传递。 So in your case 所以你的情况

var temparray1 = [this.variable1]

becomes 变成

var temparray1 = [false]

So changing it does not change variable1. 因此,更改它不会更改variable1。 But if you want to change variable1 by changing the array, you should either have variable1 as an array or object. 但是,如果要通过更改数组来更改variable1,则应该将variable1作为数组或对象。 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. 同样,Javascript也按值传递,但现在this.variable1是对对象的引用,而temparray1 [0]具有variable1的值,因此它也是对同一对象的引用。因此,我们正在更改该对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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