Javascript 访问名称为字符串的对象

Javascript 访问名称为字符串的对象,javascript,html,canvas,Javascript,Html,Canvas,我有许多仪表声明如下: var g1 = new RadialGauge({ renderTo: 'gauge1', width: 300, height: 300, units: 'Grados', title: "Temp_d9", valueBox: true, animationRule: 'bounce', animationDuration: 500 }).draw(); 名称为g1..g2..g3..g10 如果要更

我有许多仪表声明如下:

var g1 = new RadialGauge({
    renderTo: 'gauge1',
    width: 300,
    height: 300,
    units: 'Grados',
    title: "Temp_d9",
    valueBox: true,
    animationRule: 'bounce',
    animationDuration: 500
}).draw();
名称为g1..g2..g3..g10

如果要更改仪表的值,请执行以下操作:

g1.value = 10;
我想做的是改变for循环中所有仪表的值。。我尝试过的,当然没有成功:

for(var i = 1; i <= 10 ; i ++){
    var name = "t" + i;
    name.value = lst_val;
}

for(var i=1;i您应该使用数组:

gauges = []
gauges.push(new RadialGauge(...))
gauges.push(new RadialGauge(...))
gauges.push(new RadialGauge(...))
gauges.forEach(g => g.draw());

//change the values later
gauges.forEach(g => {
    var name = "t" + i;
    ...
    g.value = 123;
});
下面是一个完整的工作示例,说明这可能是什么样子:
class RadialGauge{
构造函数(ctx、x、y、颜色){
this.ctx=ctx;
这个颜色=颜色;
这个.x=x;这个.y=y;
该值为0
}
画(){
this.ctx.beginPath();
this.ctx.fillStyle=this.color;
this.ctx.arc(this.x,this.y,22,0,2*Math.PI);
这个.ctx.fill();
this.ctx.beginPath();
this.ctx.moveTo(this.x,this.y)
var x=this.x+Math.sin(this.value/10)*20;
var y=this.y+Math.cos(this.value/10)*20;
this.ctx.lineTo(x,y)
这个.ctx.stroke();
}
}
const canvas=document.getElementById('c');
const ctx=canvas.getContext('2d');
仪表=[]
压力表推压(新半径(ctx,50,50,“红色”))
压力表。推压(新半径(ctx,150,50,“蓝色”))
压力表推压(新半径(ctx,100,100,“绿色”))
压力表。forEach(g=>g.draw());
函数重画(){
ctx.clearRect(0,0400)
表.forEach(g=>{
g、 价值观++
g、 画()
});
}
设置间隔(重新绘制,20);

您应该使用数组:

gauges = []
gauges.push(new RadialGauge(...))
gauges.push(new RadialGauge(...))
gauges.push(new RadialGauge(...))
gauges.forEach(g => g.draw());

//change the values later
gauges.forEach(g => {
    var name = "t" + i;
    ...
    g.value = 123;
});
下面是一个完整的工作示例,说明这可能是什么样子:
class RadialGauge{
构造函数(ctx、x、y、颜色){
this.ctx=ctx;
这个颜色=颜色;
这个.x=x;这个.y=y;
该值为0
}
画(){
this.ctx.beginPath();
this.ctx.fillStyle=this.color;
this.ctx.arc(this.x,this.y,22,0,2*Math.PI);
这个.ctx.fill();
this.ctx.beginPath();
this.ctx.moveTo(this.x,this.y)
var x=this.x+Math.sin(this.value/10)*20;
var y=this.y+Math.cos(this.value/10)*20;
this.ctx.lineTo(x,y)
这个.ctx.stroke();
}
}
const canvas=document.getElementById('c');
const ctx=canvas.getContext('2d');
仪表=[]
压力表推压(新半径(ctx,50,50,“红色”))
压力表。推压(新半径(ctx,150,50,“蓝色”))
压力表推压(新半径(ctx,100,100,“绿色”))
压力表。forEach(g=>g.draw());
函数重画(){
ctx.clearRect(0,0400)
表.forEach(g=>{
g、 价值观++
g、 画()
});
}
设置间隔(重新绘制,20);

如果仪表变量
t1
,…,
t10
被定义为全局变量,那么您可以在
窗口['t'+i]
中为
循环
i
处理它们


但是@Helder Sepulveda建议将它们保存在一个公共数组对象(
仪表
)中,这是有道理的,因为这样可以避免名称冲突。

如果仪表变量
t1
,…,
t10
被定义为全局变量,那么您可以将它们作为
窗口['t'+i]来处理
在您的
中进行
循环
i


但是@Helder Sepulveda建议将它们保存在一个公共数组对象中(
gauges
),因为这样可以避免名称冲突。

您有多少个仪表?数字不同,一个用户可能有3个仪表,但另一个用户可能有10个仪表,这是最大值,这就是为什么我会尝试进行此操作的原因。您有多少个仪表?数字不同,一个用户可能有3个仪表,但另一个用户可能有10个仪表,这是最大值,这就是为什么我们需要我正在努力做这件事