简体   繁体   English

JavaScript。 试图简化代码,也许是循环?

[英]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.

相关问题 在尝试用html canvas和javascript绘制塞舌尔标志后尝试使用数组或循环来简化我的代码 - am trying to use arrays or loops to simplify my code after drawing Seychelles flag with html canvas and javascript 在Javascript中寻找选项算法的排列。 也许…? - Looking for Permutations of Options algorithm in Javascript. Maybe…? 用类和循环简化JavaScript? - simplify javascript with class and loops? 如何简化嵌套JavaScript循环 - How to simplify nested JavaScript loops 简化 Javascript 中的嵌套循环 function - Simplify nested loops function in Javascript PHP和Javascript。 代码优化 - PHP and Javascript. Code optimization 尝试简化JavaScript中的方程式 - Trying to simplify an equation in JavaScript 问题:尝试使用 Javascript 编码时,“未捕获的类型错误:无法读取 null 的属性‘getContext’”。 更多信息如下 - Problem with : "Uncaught TypeError: Cannot read property 'getContext' of null" when trying to code with Javascript. Further information below 试图在React,Javascript中将我的代码拆分成多个页面。 收到多个错误 - Trying to split my code into multiple pages in React, Javascript. Receiving multiple errors 我一直在尝试使用 JavaScript 跟踪我网站上发生的事件。但是该代码不起作用 - I have been trying to track Events occurring in my website using JavaScript. But that code is not working
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM