[英]JavaScript. Trying to simplify code, maybe with loops?
I'm very new to coding and I have been playing around with charts.js.我对编码很陌生,我一直在玩 charts.js。 I have this function that inserts the data into de chart, but I have to repeat the push method and the if with every array of data, so far there is only two datasets but I plan to add more and I don't want to have to repeat the some code everytime If had 15 datasets.
我有这个将数据插入图表的函数,但我必须对每个数据数组重复 push 方法和 if,到目前为止只有两个数据集,但我计划添加更多,我不想有每次重复一些代码 如果有 15 个数据集。 I'm sure there is a simpler way to do it, maybe with a loop, a forEach, with .map?
我确定有一种更简单的方法可以做到这一点,也许使用循环、forEach 和 .map? But I don't have enough grasp of javaScript yet to make it work.
但是我对 javaScript 还没有足够的了解来使它工作。 Some help would be very much apreciated.
非常感谢一些帮助。
This is the function I want to simplify:这是我想简化的功能:
function add_data(chart, labels, data) {
var today = new Date();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
graficaConexiones.data.datasets[0].data.push(randomData());
graficaConexiones.data.datasets[1].data.push(randomData());
graficaConexiones.data.labels.push(time);
if (graficaConexiones.data.datasets[0].data.length > dataLength) {
graficaConexiones.data.datasets[0].data.shift();
}
if (graficaConexiones.data.datasets[1].data.length > dataLength) {
graficaConexiones.data.datasets[1].data.shift();
}
if (graficaConexiones.data.labels.length > labelLength) {
graficaConexiones.data.labels.shift()
}
graficaConexiones.update();
}
setInterval(add_data, 5000);
I tried doing this inside the function, but I got stuck there and have no idea how to continue.我尝试在函数内部执行此操作,但我被困在那里并且不知道如何继续。
var dataGraph = graficaConexiones.data.datasets
for (let i = 0; i < dataGraph.length; i++) {
console.log(dataGraph[i]);
}
This is the complete javascript page:这是完整的 javascript 页面:
var randomData = function () {
return Math.round(Math.random() * 10);
};
var dataLength = 10;
var labelLength = 10;
var today = new Date();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
var ctx = document.getElementById("graficaConexiones");
var graficaConexiones = new Chart(ctx, {
type: 'line',
data: {
labels: ['', '', '', '', '', '', '', '', '', ''],
datasets: [{
label: "Total conexiones",
data: [null, null, null, null, null, null, null, null, null, null],
borderColor: "#DD0000",
backgroundColor: "#DD0000",
fill: false
},
{
label: "Total entrantes",
data: [null, null, null, null, null, null, null, null, null, null],
borderColor: "#1E90FF",
backgroundColor: "#1E90FF",
fill: false
},
]
},
options: {
responsive: true,
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
},
title: {
display: true,
text: 'Número de conexiones'
}
}
});
function add_data(chart, labels, data) {
var today = new Date();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
graficaConexiones.data.datasets[0].data.push(randomData());
graficaConexiones.data.datasets[1].data.push(randomData());
graficaConexiones.data.labels.push(time);
if (graficaConexiones.data.datasets[0].data.length > dataLength) {
graficaConexiones.data.datasets[0].data.shift();
}
if (graficaConexiones.data.datasets[1].data.length > dataLength) {
graficaConexiones.data.datasets[1].data.shift();
}
if (graficaConexiones.data.labels.length > labelLength) {
graficaConexiones.data.labels.shift()
}
graficaConexiones.update();
}
setInterval(add_data, 5000);
and the html:和 html:
<!DOCTYPE html>
<html>
<head>
<title>Conexiones</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="wrapper">
<h1>Conexiones</h1>
<h2>Número de conexiones</h2>
<canvas id="graficaConexiones" width="1600" height="900"></canvas>
</div>
<script src="lineChart.js"></script>
</body>
</html>
Just forEach
over the graficaConexiones.data.datasets
array:只是在
graficaConexiones.data.datasets
数组上的forEach
:
graficaConexiones.data.datasets.forEach(({ data }) => {
data.push(randomData());
if (data.length > dataLength) {
data.shift();
}
});
In full:在全:
function add_data() {
const { labels, datasets } = graficaConexiones.data;
var today = new Date();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
labels.push(time);
if (labels.length > labelLength) {
labels.shift();
}
datasets.forEach(({ data }) => {
data.push(randomData());
if (data.length > dataLength) {
data.shift();
}
});
}
Or, if you're not comfortable with destructuring:或者,如果您对解构不满意:
function add_data() {
const labels = graficaConexiones.data.labels;
const datasets = graficaConexiones.data.datasets;
var today = new Date();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
labels.push(time);
if (labels.length > labelLength) {
labels.shift();
}
datasets.forEach((dataset) => {
const data = dataset.data;
data.push(randomData());
if (data.length > dataLength) {
data.shift();
}
});
}
Extracting repeated property accesses into variables first really helps reduce repeated code.首先将重复的属性访问提取到变量中确实有助于减少重复代码。
Since you aren't passing any arguments to add_data
, remove all arguments from its definition.由于您没有将任何参数传递给
add_data
,请从其定义中删除所有参数。
With async/await the function could be simplified to a loop:使用 async/await 函数可以简化为一个循环:
const delay = ms => new Promise(res => setTimeout(res, ms));
function today() {
const today = new Date();
return today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
}
async function updateLoop() {
const { datasets, labels } = graficaConexiones.data;
for(let i = 0; i < Math.Infinity; i++) {
for(const set of datasets)
set.data.push(randomData());
labels.push(today());
for(const set of [...datasets, labels])
if(set.length > dataLength) set.shift();
graficaConexiones.update();
await delay(500);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.