如何解决javascript将数据存储在全局变量数组中或其他更好的方法
在electronic / node.js中,我正在尝试执行以下操作
-
从excel / csv读取数据
-
使用d3.js绘制数据
-
清除数据(删除重复的数据,等等)
-
使用数据进行一些计算
脚本的伪结构如下所示
const {remote} = require('electron');
var dialog = remote.dialog;
var dataArr = new array(); //in global scope
function readData(){
empty(dataArr); //make sure the global array uis empty
dialog.showOpenDialog(...). //show a file open dialog
then(...); //read the XLSX/CSV file
//save the data to dataArr,as an array of object.
//[{Time:,pressure: },...]
clean(dataArr);
draw(dataArr);
}
function empty(arr){ //empty the array
while(arr.length){
arr.pop();
}
}
function clean(res){
//make sure the time stamp in chronological order
//make sure there is no duplicated record with same time stamp.
}
function draw(res){
//draw the array of objects with d3.js
}
function calculate(res){
//use the res to do calculation
//return some results
}
readData();
calculate(dataArr);
脚本运行正常。但是我发现它看起来有些混乱,因为dataArr有时会传递给函数,有时会作为全局数组进行访问。
我在互联网上看到说应该避免使用全局变量。但是在这种情况下,我不确定应该遵循哪些规则或示例来改进代码,以使代码不易出现问题。
欢迎任何建议。预先感谢。
解决方法
不需要使用全局变量,因为您已经混合了全局变量和局部变量。让readData
返回数组。
const {remote} = require('electron');
var dialog = remote.dialog;
function readData(){
var dataArr = new array(); //in local scope
empty(dataArr); //make sure the local array uis empty
dialog.showOpenDialog(...). //show a file open dialog
then(...); //read the XLSX/CSV file
//save the data to dataArr,as an array of object.
//[{Time:,pressure: },...]
clean(dataArr);
draw(dataArr);
return dataArr;
}
function empty(arr){ //empty the array
while(arr.length){
arr.pop();
}
}
function clean(res){
//make sure the time stamp in chronological order
//make sure there is no duplicated record with same time stamp.
}
function draw(res){
//draw the array of objects with d3.js
}
function calculate(res){
//use the res to do calculation
//return some results
}
calculate(readData());
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。