简体   繁体   中英

How to change array variable name dynamically

I am working for some common method in javascript, for that i have to call array dynamically.

 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();
    };

I want to call array ddlTextCacheList_Scale or ddlTextCacheList_Designation for same method as we know 'ddlTextCacheList_' is common only we need to put 'Scale' or 'Designation' dynamicaaly by passing parameter.

Add:
I get some errors:
在此处输入图片说明

I suggest you to improve your cache to store all in one object to easy access...
For example:

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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