简体   繁体   中英

Storing a set of variables with set values in javascript using an array

To begin with, I'm COMPLETELY new to js. A week ago the company I work for moved me from a manual labor job to web development because I'm cheap, learn quickly and have some IT/programming experience (but 0 web development experience).

I'm working on a form for ordering a system my company makes. I have a set of part # variables with set values. I need them to equal 1 part number, while storing both the name of the original variable and there original values. If I use an array to do this, will I loose the original variable name when it index's?

I've read all of the w3s pages on arrays and variables. I also read about objects and was wondering if creating this as an object might be a better solution.

This is the code I've got.

case '16 x 32':

        var Pn_VTP1632PKN_qty = [var Pn_VFH2014_qty = 1, var Pn_52001_qty = 4, var Pn_55015_qty = 2, var Pn_SDT3011_qty = 4, var Pn_10507_qty = 2, var Pn_PAC1007_qty = 1, var Pn_UT22674_qty = 3, var Pn_55031_qty = 3];
        var Pn_VTP1632PKA_qty = [var Pn_VFH2014_qty = 1, var Pn_52001_qty = 4, var Pn_55015_qty = 2, var Pn_SDT3011_qty = 4, var Pn_10507_qty = 2, var Pn_PAC1007_qty = 1, var Pn_UT22674_qty = 3, var Pn_55031_qty = 3,
             var Pn_55024_qty = 8, var Pn_AC0002_qty = 1, var Pn_22116_qty = 7];

        if(trim($('#Include_Aluminum_Coping option:selected').text()) == 'Yes') {
            Pn_VTP1632PKA_qty;
        } else {
            Pn_VTP1632PKN_qty;
        }

        TS = 193;
        TL = 396;

It sounds like you want an object rather than an array. Something like:

var Pn_VTP1632PKN_qty = { 
    Pn_VFH2014_qty : 1, 
    Pn_52001_qty : 4, 
    Pn_55015_qty : 2,
    // an so on...
};

Now you can quickly (ugly variable names apart) find out the number of Pn_VFH2014_qty like this:

var howMany = Pn_VTP1632PKN_qty.Pn_VF2014_qty;  

You can loop through all the components with something like this:

for (var key in Pn_VTP1632PKN_qty) {
   if (Pn_VTP1632PKN_qty.hasOwnProperty(key)) {
       console.log(key + ":" Pn_VTP1632PKN_qty[key]);
   }
}

But I suspect you should look for a better way to handle your data because it looks like you are trying to hard code a lot of data into a webpage that ought to be retrieved from, for example, a web service that connects to a database.

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