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());

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...