在electron/node.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());
关于javascript - javascript将数据存储在全局变量数组中(或其他更好的方法),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63445117/