Javascript 如何在循环内创建动态变量名?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8260156/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I create dynamic variable names inside a loop?
提问by Philipp Bergmann
I'm working on an ajax google maps script and I need to create dynamic variable names in a for loop.
我正在处理 ajax 谷歌地图脚本,我需要在 for 循环中创建动态变量名称。
for (var i = 0; i < coords.length; ++i) {
var marker+i = "some stuff";
}
What I want to get is: marker0
, marker1
, marker2
and so on.
and I guess there is something wrong with marker+i
我想得到的是:marker0
, marker1
,marker2
等等。我想有什么问题marker+i
Firebug gives me this: missing ; before statement
Firebug 给了我这个: missing ; before statement
回答by JohnP
Use an array for this.
为此使用数组。
var markers = [];
for (var i = 0; i < coords.length; ++i) {
markers[i] = "some stuff";
}
回答by Todd Ditchendorf
I agree it is generally preferable to use an Array
for this.
我同意通常最好为此使用 an Array
。
However, this can also be accomplished in JavaScript by simply adding properties to the current scope (the global scope, if top-level code; the function scope, if within a function) by simply using this
– which always refers to the current scope.
然而,这也可以在 JavaScript 中通过简单地通过简单地使用– 始终指代当前范围,通过简单地将属性添加到当前范围(全局范围,如果是顶级代码;函数范围,如果在函数内)this
来实现。
for (var i = 0; i < coords.length; ++i) {
? ? this["marker"+i] = "some stuff";
}
You can later retrieve the stored values (if you are within the same scope as when they were set):
您可以稍后检索存储的值(如果您在设置它们时的范围内):
var foo = this.marker0;
console.log(foo); // "some stuff"
This slightly odd feature of JavaScript is rarely used (with good reason), but in certain situations it can be useful.
JavaScript 的这个有点奇怪的特性很少使用(有充分的理由),但在某些情况下它可能很有用。
回答by Safiq
Try this
尝试这个
window['marker'+i] = "some stuff";
回答by kayleeFrye_onDeck
In regards to iterative variable names, I like making dynamic variables using Template literals. Every Tom, Dick, and Harry uses the array-style, which is fine. Until you're working with arrays anddynamic variables, oh boy! Eye-bleed overload. Since Template literals have limited support right now, eval()
is even another option.
关于迭代变量名,我喜欢使用模板文字制作动态变量。每个 Tom、Dick 和 Harry 都使用数组样式,这很好。在您使用数组和动态变量之前,天哪!眼出血过载。由于模板文字现在支持有限,eval()
因此甚至是另一种选择。
v0 = "Variable Naught";
v1 = "Variable One";
for(i = 0; i < 2; i++)
{//console.log(i) equivalent is console.log(`${i}`)
dyV = eval(`v${i}`);
console.log(`v${i}`); /* => v0; v1; */
console.log(dyV); /* => Variable Naught; Variable One; */
}
When I was hacking my way through the APIs I made this little looping snippet to see behavior depending on what was done with the Template literals compared to say, Ruby. I liked Ruby's behavior more; needing to use eval()
to get the value is kind of lame when you're used to getting it automatically.
当我通过 API 破解我的方式时,我制作了这个小循环片段来查看行为,这取决于与 Ruby 相比,模板文字所做的事情。我更喜欢Ruby的行为;需要使用eval()
获得的价值是一种跛脚的,当你使用自动得到它。
_0 = "My first variable"; //Primitive
_1 = {"key_0":"value_0"}; //Object
_2 = [{"key":"value"}] //Array of Object(s)
for (i = 0; i < 3; i++)
{
console.log(`_${i}`); /* var
* => _0 _1 _2 */
console.log(`"_${i}"`); /* var name in string
* => "_0" "_1" "_2" */
console.log(`_${i}` + `_${i}`); /* concat var with var
* => _0_0 _1_1 _2_2 */
console.log(eval(`_${i}`)); /* eval(var)
* => My first variable
Object {key_0: "value_0"}
[Object] */
}
回答by Md Junaid Alam
You can use eval() method to declare dynamic variables. But better to use an Array.
您可以使用 eval() 方法来声明动态变量。但最好使用数组。
for (var i = 0; i < coords.length; ++i) {
var str ="marker"+ i+" = undefined";
eval(str);
}
回答by vikram prajapat
var marker = [];
for ( var i = 0; i < 6; i++) {
marker[i]='Hello'+i;
}
console.log(marker);
alert(marker);
回答by Alfgaar
var marker+i = "some stuff";
coudl be interpreted like this: create a variable named marker (undefined); then add to i; then try to assign a value to to the result of an expression, not possible. What firebug is saying is this: var marker; i = 'some stuff'; this is what firebug expects a comma after marker and before i; var is a statement and don't (apparently) accepts expressions. Not so good an explanation but i hope it helps.
可以这样解释:创建一个名为标记(未定义)的变量;然后加到我;然后尝试为表达式的结果赋值,不可能。firebug 的意思是: var 标记;i = '一些东西'; 这就是萤火虫期望在标记之后和 i 之前有一个逗号;var 是一个语句,不(显然)接受表达式。不是很好的解释,但我希望它有所帮助。