简体   繁体   English

根据用户输入动态创建和覆盖变量

[英]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. 在下面的代码中,用户可以通过输入类型文本元素利用window对象创建变量。 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. 我编写了一个函数,该控制台将记录变量的名称,后跟变量初始化的值0 This only occurs when the following key string literal, "-nr " precedes the desired name for the created variable. 仅当以下关键字字符串文字"-nr "位于所创建变量的所需名称之前时,才会发生这种情况。

The goal of this exercise is to increment any created variable value by 1 when the variable name is reentered into the input element. 本练习的目的是在将变量名称重新输入到输入元素中时,将所有创建的变量值加1 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. 我这样做的尝试是,首先编写第一个函数varCreate以将变量声明为0 push其初始化为0pushpush入数组,然后在控制台中记录变量名及其值。 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 . 我有(一个问题下一功能varPlus )是指加1时被输入到然而所述输入元件的特定名称给每个值的值时,它增加了一些超过1 ,甚至当我利用for循环到计算输入元素value属性的字符串文字值是否等效于数组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. 尝试使用varPlus时的最终结果是,它将控制台记录所有变量名和变量,而这些值和变量只能以控制台方式记录仅我尝试通过用户输入访问的变量名及其值。 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. 哦是的,语法很简单: <name> = <value>例如。 foo = 10 .. unimportant detail :P foo = 10 ..不重要的细节:P

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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