通过引用将JavaScript数组传递给局部变量? [英] Pass JavaScript array to local variable by reference?
问题描述
我在这样的名称空间中有一个JavaScript数组:
I have a JavaScript array inside a namespace like this:
app.collec.box = [];
并且我在同一个名称空间中有一个函数,如下所示:
and I have a function inside the same namespace like this:
app.init = function () {
var box = this.collec.box;
// ... code to modify box
};
我认为将局部变量设置为等于对象或对象属性只是对原始变量的引用,但是在更改函数app.collec.box
中局部box
变量的内容之后,看来我错了不会改变.
I thought that setting a local variable equal to an object or object property was just a REFERENCE to the original, but it seems I am wrong, after changing the contents of the local box
variable inside my function, app.collec.box
does not change.
请帮助,我在做什么错?我该如何解决?
Please help, what am I doing wrong? how can I solve this?
谢谢.
编辑..这是完整的代码.
var app = {
collec: {
box: [],
cache: []
},
init: function () {
var box = this.collec.box;
$.ajax({
url: 'file.json',
success: function (json) {
// Map JSON array to box array using Underscore.js _()map
box = _(json).map(function (o) {
return new Model(o);
});
}
});
}
};
app.init();
推荐答案
引用指向对象,而不是变量. box
不是对变量this.collec.box
的引用;而是box
和this.collec.box
是对内存中一个特定对象的引用.您可以通过这两个变量之一来修改此对象的属性,但是不能使用一个变量来修改另一个变量.
References point to objects, not variables. box
is not a reference to the variable this.collec.box
; rather, box
and this.collec.box
are references to one specific object in memory. You can modify the properties of this object through either of these variables, but you can't use one variable to modify another variable.
如果要修改this.collec.box
所指的内容,则需要像这样直接设置它:
If you want to modify what this.collec.box
refers to, you either need to set it directly like this:
this.collec.box = ...;
或使用对this.collec
对象的引用并修改其box
属性:
or use a reference to the this.collec
object and modify its box
property:
var x = this.collec;
x.box = ...;
编辑:也许有几个图表可以使您更容易理解正在发生的事情.
Maybe a couple of diagrams will make it easier to understand what's happening.
分配box = this.collec.box
时,实际上是这样:
When you assign box = this.collec.box
, this is what actually happens:
this.collec.box -----> (object) <----- box
这两个变量都指向内存中的同一对象,但是box
绝没有引用this.collec.box
变量.
Both the variables point to the same object in memory, but in no way does box
actually refer to the this.collec.box
variable.
如果发生这种情况,您期望的结果将起作用:
What you are expecting would work if this happened:
box -----> this.collec.box -----> (object)
但这不会发生.
这篇关于通过引用将JavaScript数组传递给局部变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!