访问名称为字符串的对象

我有许多仪表声明如下:


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;

}

我怎样才能做到这一点?这是可能的?谢谢


qq_笑_17
浏览 152回答 2
2回答

慕神8447489

如果您的仪表变量t1,...,t10被定义为全局变量,那么您可以window['t'+i]在for循环中处理它们i。但是@Helder Sepulveda 建议将它们保存在一个通用的数组对象 (&nbsp;gauges) 中,因为这样可以避免名称冲突。

慕码人2483693

您应该使用数组:gauges = []gauges.push(new RadialGauge(...))gauges.push(new RadialGauge(...))gauges.push(new RadialGauge(...))gauges.forEach(g => g.draw());//change the values latergauges.forEach(g => {&nbsp; &nbsp; var name = "t" + i;&nbsp; &nbsp; ...&nbsp; &nbsp; g.value = 123;});这是一个完整的工作示例,说明它的外观:class RadialGauge {&nbsp; constructor(ctx, x, y, color) {&nbsp; &nbsp; this.ctx = ctx;&nbsp; &nbsp; this.color = color;&nbsp; &nbsp; this.x = x; this.y = y;&nbsp; &nbsp; this.value = 0&nbsp; }&nbsp;&nbsp;&nbsp; draw() {&nbsp; &nbsp; this.ctx.beginPath();&nbsp; &nbsp; this.ctx.fillStyle = this.color;&nbsp; &nbsp; this.ctx.arc(this.x, this.y, 22, 0, 2 * Math.PI);&nbsp; &nbsp; this.ctx.fill();&nbsp; &nbsp; this.ctx.beginPath();&nbsp; &nbsp; this.ctx.moveTo(this.x, this.y)&nbsp; &nbsp; var x = this.x + Math.sin(this.value/10) * 20;&nbsp; &nbsp; var y = this.y + Math.cos(this.value/10) * 20;&nbsp; &nbsp; this.ctx.lineTo(x, y)&nbsp; &nbsp; this.ctx.stroke();&nbsp; }}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() {&nbsp; ctx.clearRect(0,0,400,400)&nbsp; gauges.forEach(g => {&nbsp;&nbsp;&nbsp; &nbsp; g.value++&nbsp; &nbsp; g.draw()&nbsp; });}setInterval(reDraw, 20);<canvas id="c" width=400 height=150></canvas>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript