[英]How to update object values with array variables? (JavaScript)
I have an object variable storing bar chart values and a button to update those values: 我有一个存储条形图值的对象变量和一个用于更新这些值的按钮:
var config = { type: 'bar', data: { datasets: [{ type: 'bar', label: 'Dataset 1', data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]}]}}; document.getElementById('add5').addEventListener('click', function() { tnow = moment().format('HH'); switch (tnow) { case'8': config.data.datasets[0].data[0] += 5; break; case'9': config.data.datasets[0].data[1] += 5; break; // ... case'23': config.data.datasets[0].data[15] += 5; break; case'24': config.data.datasets[0].data[16] += 5; break; default: alert('doot');} window.myLine.update()});
<button id="add5">+5</button>
I seek to store the value pointer as a variable to shorten the code. 我试图将值指针存储为变量以缩短代码。 Tried
试过了
var h = [];
var h = config.data.datasets[0].data.slice();
but 但
case '23': h[15] += 5; break;
does not update the bar chart value. 不更新条形图的值。
alert(h[15])
does, however, return the accurate chart value. alert(h[15])
确实会返回准确的图表值。
How can I update the chart values using array variables? 如何使用数组变量更新图表值?
FULL CONTEXT: 全文:
Using moment.js and chart.js to generate a bar graph that updates a value according to a real-time clock. 使用moment.js和chart.js生成条形图,该条形图根据实时时钟更新值。 Ex: if it's 7:30PM, clicking '+5' will add 5 to the bar located at 7PM.
例如:如果是晚上7:30,则单击“ +5”会将5添加到位于晚上7点的栏中。
case '8'
= 8AM, case '23'
= 11PM, etc. I intend to add a second dataset which gets displayed when values exceed 60, using an if
to modify the second dataset's value ( involving config.data …
twice more - making the code pretty lengthy). case '8'
= 8AM, case '23'
= 11PM,依此类推。我打算添加第二个数据集,当值超过60时将显示该数据集,使用if
修改第二个数据集的值(涉及config.data …
两次以上-使代码很长)。
When you use slice()
: 当您使用
slice()
:
var h = config.data.datasets[0].data.slice();
you are making a copy of config.data.datasets[0].data
. 您正在复制
config.data.datasets[0].data
。 You then alter that copy in your code, but this has no effect on the bar chart because it doesn't change the original data: 然后,您可以在代码中更改该副本,但这对条形图没有影响,因为它不会更改原始数据:
let datasets = [{ data: [1, 2, 3, 4, 5, 6] }] let h = datasets[0].data.slice() h[0] ="What?" console.log(h) // h has changed console.log(datasets[0].data) // original data is unchanged console.log(h === datasets[0].data) // because they are not the same array
If you want to shorten your code, just take a reference to the array without slice()
: 如果要缩短代码,只需引用不带
slice()
的数组即可:
var h = config.data.datasets[0].data
let datasets = [{ data: [1, 2, 3, 4, 5, 6] }] let h = datasets[0].data h[0] ="What?" console.log(h) // h has changed console.log(datasets[0].data) // original data is also chaged console.log(h === datasets[0].data) // because they ARE the same array
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.