简体   繁体   中英

Creating and overwriting variables dynamic per user input

In the following code, the user is able to create variables utilizing the window object via an input type text element. I've written a function that console logs the name of the variable followed by the value of 0 in which the variable is initialized. This only occurs when the following key string literal, "-nr " precedes the desired name for the created variable.

The goal of this exercise is to increment any created variable value by 1 when the variable name is reentered into the input element. My attempt at doing so is by first writing the first function, varCreate to declare and initialize variables to 0 , push them into an array, and console log the variable name followed by its value. The next function which I have a problem with ( varPlus ) is meant to add 1 to the value of each value when a particular name is entered into the input element however, it adds a few more than 1 even when I utilize a for loop to evaluate if the string literal value of the input element value property is equivalent to each element of the array varArray .

const _in = document.getElementById('in');

var varArray = [];

function varCreate(e) {

    let _key = e.key;
    if(_key === "Enter") {

        if(_in.value.substring(0, 4) == "-nr ") {

            window[_in.value.substring(4).replace(/\s/g, "_")] = 0;
            varArray.push(_in.value.substring(4).replace(/\s/g, "_"));
            console.log("var: " + varArray[varArray.length - 1] + "\nvalue: " + window[varArray[varArray.length - 1]]);

            _in.value = "";

        }

    }

}

function varPlus(e1) {

    let _key1 = e1.key;
    if(_key1 === "Enter") {

        checker = new RegExp(_in.value.replace(/\s/g, "_"), "gi");
        for(var i = 0; i < varArray.length; i++) {

            if(checker.test(varArray[i])) {

                window[varArray[i]] += 1;
                console.log("var: " + varArray[i] + "\nvalue: " + window[varArray[i]]);

            }

        }

        delete window["checker"];

    }

}

_in.addEventListener('keydown', varCreate);
_in.addEventListener('keydown', varPlus);
<input id='in' type='text' />

The end result when attempting to utilize varPlus is that it'll console log all variable names and values which somehow increment in value when it should only be console logging only the variable name which I'm trying to access via user input followed by its value. I would greatly appreciate it if anyone can shed some light on how I'm encountering these errors.

First of all it is really helpful if you try and make your code executable :)

Now for the user generated variables you could do something like this:

 // DOM Elements const input_variable = document.getElementById("input_variable"); const button_createVariable = document.getElementById("button_createVariable"); // Variables let userVariables = {}; // Event listeners window.addEventListener("keyup", event => {if(event.key == "Enter") parseVariable()}); button_createVariable.addEventListener("click", parseVariable); function parseVariable() { // Get the variable name and remove all spaces let variableName = input_variable.value.substring(0, input_variable.value.indexOf("=")).replace(/\\s+/g, ''); // Get the variable value and remove all spaces let variableValue = input_variable.value.substring(input_variable.value.indexOf("=") + 1, input_variable.value.length).replace(/\\s+/g, ''); // Add the variable to the object userVariables[variableName] = variableValue; // Clear the input input_variable.value = ""; // Log the object into the console console.log(userVariables); } 
 <input id='input_variable' type='text'/><button id="button_createVariable">Create</button> 

WARNING You of course still need to verify the user input. At this state it will accept everything as input. But now you can loop through the object and count up (or whatever) if already exists.

Oh yes btw, the syntax is simply: <name> = <value> eg. foo = 10 .. unimportant detail :P

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