为了账号安全,请及时绑定邮箱和手机立即绑定

访问名称为字符串的对象

访问名称为字符串的对象

qq_笑_17 2022-06-05 09:49:18
我有许多仪表声明如下: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;}我怎样才能做到这一点?这是可能的?谢谢
查看完整描述

2 回答

?
慕神8447489

TA贡献1780条经验 获得超1个赞

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

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


查看完整回答
反对 回复 2022-06-05
?
慕码人2483693

TA贡献1860条经验 获得超9个赞

您应该使用数组:


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 {

  constructor(ctx, x, y, color) {

    this.ctx = ctx;

    this.color = color;

    this.x = x; this.y = y;

    this.value = 0

  }

  

  draw() {

    this.ctx.beginPath();

    this.ctx.fillStyle = this.color;

    this.ctx.arc(this.x, this.y, 22, 0, 2 * Math.PI);

    this.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)

    this.ctx.stroke();

  }

}


const canvas = document.getElementById('c');

const ctx = canvas.getContext('2d');


gauges = []

gauges.push(new RadialGauge(ctx, 50, 50, "red"))

gauges.push(new RadialGauge(ctx, 150, 50, "blue"))

gauges.push(new RadialGauge(ctx, 100, 100, "green"))

gauges.forEach(g => g.draw());


function reDraw() {

  ctx.clearRect(0,0,400,400)

  gauges.forEach(g => {  

    g.value++

    g.draw()

  });

}

setInterval(reDraw, 20);

<canvas id="c" width=400 height=150></canvas>


查看完整回答
反对 回复 2022-06-05
  • 2 回答
  • 0 关注
  • 151 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号