使用两个变量的内容并将其用作一个变量 [英] use content of two variables and use it as one
本文介绍了使用两个变量的内容并将其用作一个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这可能是一个非常基本的问题,但我真的不明白发生了什么。
This might be a very basic question but I don't really get understand what is happening.
如果我有一些 var
s在Javascript中如下:
If I have a few var
s in Javascript like below:
var cube1 = paper.rect(200, 200, 0, 0);
var cube2 = paper.rect(300, 200, 0, 0);
...
它转到 cube99
。
要捕获所有多维数据集我在循环中执行以下操作:
To catch all cubes in I'm doing the following in a loop:
for(var i = 0; i < 100; i++) {
cube+i.attr(fill: '#000');
console.log(i);
}
但它会抛出一个未定义的错误,即多维数据集不可用。
but it throws me an undefined error that "cube isn't available".
为什么会这样?
推荐答案
假设你的变量是全局的,然后它们是窗口
对象的属性。您可以使用括号表示法:
Supposing your variables are global, then they're property of the window
object. You can use the bracket notation :
window['cube'+i].attr(fill: '#000');
但更好的做法是将所有多维数据集存储在一个数组中:
But a better practice would be to store all your cubes in an array :
var cubes = [];
cubes.push(paper.rect(200, 200, 0, 0));
...
for(var i = 0; i < 100; i++) {
cubes[i].attr(fill: '#000');
...
}
这篇关于使用两个变量的内容并将其用作一个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文