简体   繁体   English

如何创建在 JavaScript 中生成新变量的 function?

[英]How do I create a function that generates new variables in JavaScript?

I know that there might be tons of the same question here, but being a noob I can't really understand them.我知道这里可能有很多相同的问题,但作为一个菜鸟,我无法真正理解它们。

What I'd like to do is creating a function that, once we click on a button or simply activate it, it generates a new variable accesible in all the scopes, not overwriting the previous one it generated, with a different name and a value (the value can be a parameter we pass to the function or simply something taken from an array or a Math.random(), it doesn't matter).我想做的是创建一个 function ,一旦我们单击一个按钮或简单地激活它,它就会生成一个可在所有范围内访问的新变量,而不是覆盖它生成的前一个变量,具有不同的名称和值(该值可以是我们传递给 function 的参数,或者只是从数组或 Math.random() 中获取的参数,没关系)。 The names could be the same for all variables but followed with a _2, _3, _4 etc.所有变量的名称可以相同,但后跟 _2、_3、_4 等。

How can I do it as simple as possible?我怎样才能做到尽可能简单?

Would you help me please?请你帮帮我好吗? Thanks!谢谢!

 var count = 1; var prefix = "prefix" function createVar(value) { var name = prefix + count; this[name] = value; ++count; } $("#button").click(function() { createVar("one value " + count); var name = prefix + (count - 1); console.log(window[name]); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <button id="button">Click</button>

Now, you have access to prefix_1 on first click, prefix_2 on second click,...现在,您可以在第一次单击时访问prefix_1 ,在第二次单击时访问prefix_2 ,...

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

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