Search code examples
javascriptvariableswildcardstring-matching

Can a wildcard be used to call variables in Javascript?


I have a ton of variables to work with here, with information going back and forth between a form in HTML. The variables need to be global so that they can work across a variety of functions. So here's one sample of the list:

var charDex = 0;
var charEnd = 0;
var charPer = 0;
var charStr = 0;
var charCon = 0;
var charInt = 0;
var charRat = 0;
var charRes = 0;
var charDip = 0;
var charGui = 0;
var charItd = 0;
var charLea = 0;

They start out at zero, data is entered into the form, a button sends the data into a JS function that stores the data, and then sends various information based on said stored data back to the form.

Now, I know I'm able to save some repetition by using functions within functions, which I've done so far. But still, there's a lot going on here. What I want to know is if there's a way to use wildcards and/or string matching to automatically match up data from form input to JS variables? The end result would be something to the effect of:

function updateCharacter(form){
    char* = form.c*.value;
    racial* = form.r*.value;
    mod* = form.m*.value;
    total* = char* + racial* + mod*;
    form.t*.value = total*;
}

In my case, charDex and form.cDex.value (etcetera) have the same suffix, so I figure there's something I can do, I'm just not sure what I'm missing.I thought about using a for loop with an array, but I'm not exactly certain how I could make that work.


Solution

  • No worries!

    Just use an object instead.

    edit: removing the 'char' variable name previously used, as it's a reserved word.

    var chars = {
        Dex: "some text",
        End: 0,
        Per: 2,
        Str: 345,
        Con: "blah blah",
        Int: 0,
        Rat: 0,
        Res: 0,
        Dip: 0,
        Gui: 0,
        Itd: 0,
        Lea: 0
    }
    

    You can access the values of each of these using either of the following options:

    • chars['Dex']
    • chars.Dex

    either of these will give you "some text".


    To iterate over the properties, try this:

    for (prop in chars) {
        console.log( prop ); // this will log the name of the property
        console.log( chars[prop] ); // this will log the value
    }