javascript - 限制表中的数据数量
问题描述
我将我的数据表与 websocket 连接以显示来自后端的实时数据。数据是实时提要,因此会连续添加行。
问题:当旧数据达到例如 1000 行时,如何制作数据表以删除旧数据,因此在一个表中仅显示 1000 行?
解决方案
preDraw
您可以在推送新数据时重绘数据表之前监听触发的事件。因此,您可以检查是否超出行数并查找并删除最旧的条目。
我猜这可能有效:
//define initial data sample
const srcData = [{parameter: 'CPU usage, %', value: Math.floor(Math.random()*100), timestamp: (new Date()).toString()}];
//define datatable object
const dataTable = $('#mytable').DataTable({
sDom: 't',
data: srcData,
columns: [
{title: 'parameter', data: 'parameter'},
{title: 'value', data: 'value'},
{title: 'timestamp', data: 'timestamp'}
]
});
//emulate new data insertion
const dataPooler = window.setInterval(function(){
dataTable.row.add({parameter: 'CPU usage, %', value: Math.floor(Math.random()*100), timestamp: (new Date()).toString()}).draw();
},3000);
//listen for new draws, purge oldest entry
dataTable.on('preDraw', function(){
if(dataTable.rows().count() < 5) return;
//grab the oldest entry timestamp
let oldestTimestamp = dataTable.column(2).data().toArray().map(entry => new Date(entry)).sort()[0].toString();
//look through the table and purge corresponding entry if table has more than 10 entries
let oldestEntryIndex = dataTable.column(2).data().indexOf(oldestTimestamp)
dataTable.row(oldestEntryIndex).remove();
});
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
<script type="application/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="application/javascript" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
</head>
<body>
<table id="mytable"></table>
</body>
</html>
推荐阅读
- javascript - 如何获取在文档准备好后呈现的元素?
- machine-learning - 使用数据驱动方法进行信息检索的贝叶斯网络建模?
- node.js - Docker 节点错误:“darwin-x64”二进制文件不能在“linux-x64”平台上使用
- powershell - 遍历 Invoke-WebRequest JSON 结果
- git - 用另一个远程分支更新 Git 远程分支
- graph - 在 Gremlin 中同时合并它们之间的顶点和边
- google-data-studio - 在倒数第二个冒号后提取子字符串
- python - NoReverseMatch at / Reverse for 'detail' with arguments '('',)' 未找到。尝试了 1 种模式:['posts/(?P
[0-9]+)/$'] - javascript - headerDelegate QML tableView - 文本不可见
- kotlin - kotlin 中的 data 和 dataa 属性有什么不同?