如何在javascript中通过引用调用变量?
我有一个JavaScript对象的方法,其结构如下:如何在javascript中通过引用调用变量?,javascript,variables,reference,Javascript,Variables,Reference,我有一个JavaScript对象的方法,其结构如下: performOperation: function (rel) { var currentArray = []; switch (rel) { case 'templates': currentArray = templates; break; case 'drafts': currentArray = drafts;
performOperation: function (rel) {
var currentArray = [];
switch (rel) {
case 'templates':
currentArray = templates;
break;
case 'drafts':
currentArray = drafts;
break;
case 'sent':
currentArray = sent;
break;
case 'scheduled':
currentArray = scheduled;
break;
case 'cancelled':
currentArray = cancelled;
break;
case 'inbox':
currentArray = inbox;
break;
}
// Series of operations here.
switch (rel) {
case 'templates':
templates = currentArray;
break;
case 'drafts':
drafts = currentArray;
break;
case 'sent':
sent = currentArray;
break;
case 'scheduled':
scheduled = currentArray;
break;
case 'cancelled':
cancelled = currentArray;
break;
case 'inbox':
inbox = currentArray;
break;
}
}
是否有一种方法可以通过引用要使用的数组来调用此var currentary
,即drafts、inbox、cancelled、
。在C++和PHP中,我知道我们在变量之前使用<代码>和<代码>引用。
如果有任何方法可以在JavaScript中进行此引用,欢迎所有答案。您可以将数据结构更改为对象,该对象具有您描述的访问所需的属性
var data = {
templates: [],
drafts: [],
sent: [],
scheduled: [],
cancelled: [],
inbox: []
};
function performOperation(rel) {
var currentArray = data[rel];
//
// Series of operations here.
//
data[rel] = currentArray;
}
JavaScript中没有引用调用。不可能。如果你正在操作一个对象,比如你的一个数组,你不必写回它,因为你从来没有创建过它的副本。对象是引用值。您确实希望使用对象并通过动态名称引用其属性,而不是将一堆不同的变量放在一起。