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

在数组中传递变量,而不是在javascript中传递值,javascript,actionscript-3,vue.js,vuejs2,Javascript,Actionscript 3,Vue.js,Vuejs2,是否有一种方法可以传递变量本身,而不是javascript中的值?我记得在flas as3中可以这样做,如果我记得正确的话,它是基于javascript的。我不知道为什么我不能在这里做同样的事情。非常感谢你的帮助 variable1: false, function1() { this.variable1 = true //this works of course console.log(this.variable1) prints true } function2() {

是否有一种方法可以传递变量本身,而不是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 } 变量1:false, 职能1(){ this.variable1=true//this course console.log(this.variable1)打印true } 职能2(){ var temparray1=[this.variable1] temparray1[0]=true//不能像我希望的那样工作,是数组中的值改变了,而不是这个。variable1 console.log(this.variable1)//打印仍然为false console.log(temparray1[0])//打印true }
在Javascript中无法通过引用传递
布尔值
,但作为一种解决方法,您可以将布尔值封装在对象中,如下所示:

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时,它应该为true。

Javascript总是按值传递。那么你的情况呢

var temparray1 = [this.variable1]
变成

var temparray1 = [false]
所以改变它不会改变变量1。但是,如果要通过更改数组来更改variable1,则应该将variable1作为数组或对象。例如:

this.variable1 = {
    value: false
}

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

在这里,Javascript也按值传递,但现在this.variable1是对对象的引用,temparray1[0]的值为variable1,因此它也是对同一对象的引用。因此我们正在更改该对象。

您不能这样做。这不是该语言的工作方式,这对于任何以后不得不使用您的代码的JavaScript开发人员来说都是非常混乱的。Ok的可能副本,那么如何动态实现呢。假设您有一个表,当您匹配数组中的项时,您希望更改在该索引中选择的变量。感谢您的输入。还有,我怎样才能修复这个帖子,以便解锁我的帐户,我不能发布,我不知道是什么问题。或者如何改进这个问题。谢谢