如何动态更改数组变量名称

时间:2014-12-29 11:37:06

标签: javascript

我正在为javascript中的一些常用方法工作,因为我必须动态调用数组。

 var ddlText, ddlValue, ddl, lblMesg, ddlTextCacheList_Designation, ddlValueCacheList_Designation, ddlTextCacheList_Scale, ddlValueCacheList_Scale;
 function cacheDes() {

        var listDes = document.getElementById("<%=List_Designation.ClientID %>");
        ddlTextCacheList_Designation = new Array();
        ddlValueCacheList_Designation = new Array();
        for (var i = 0; i < listDes.options.length; i++) {
            ddlTextCacheList_Designation[ddlTextCacheList_Designation.length] = listDes.options[i].text;
            ddlValueCacheList_Designation[ddlValueCacheList_Designation.length] = listDes.options[i].value;

        }


    }


    function cacheScale() {
        var listScale = document.getElementById("<%=List_Scale.ClientID %>");
        ddlTextCacheList_Scale = new Array();
        ddlValueCacheList_Scale = new Array();
        for (var i = 0; i < listScale.options.length; i++) {
            ddlTextCacheList_Scale[ddlTextCacheList_Scale.length] = listScale.options[i].text;
            ddlValueCacheList_Scale[ddlValueCacheList_Scale.length] = listScale.options[i].value;

        }


    }

    window.onload = function () {
        cacheDes();
        cacheScale();
    };

我想调用数组ddlTextCacheList_Scale或ddlTextCacheList_Designation,因为我们知道'ddlTextCacheList_'是常见的,我们需要通过传递参数来放置'Scale'或'Designation'动态。

添加
我收到一些错误:
enter image description here

1 个答案:

答案 0 :(得分:1)

我建议您改进缓存以将所有对象存储在一个对象中以便于访问...
例如:

var CacheStorage = {};
function cache(key, list) {
  CacheStorage[key] = list.map(function(option){
    return {text: option.text, value: option.value};
  });
}
function del(key, index) {
  CacheStorage[key].splice(index, 1);
}

cache('Scale', getElementByID('...').options);
cache('Designation', getElementByID('...').options);
del('Designation', 0);