javascript - javascript将数据存储在全局变量数组中(或其他更好的方法)

标签 javascript node.js arrays electron global-variables

在electron/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());
    

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

    相关文章:

    javascript - a = [ ], i, j,len 是什么意思;在javascript中, 'a'是任何变量吗?

    javascript - 查询函数?

    javascript - 为新的 div 添加独特的类

    c - 返回数组中最大的元素

    java - 尝试将消息中的字母转换为数字时没有得到任何输出

    javascript - [1, 2] 中的 0 == true,为什么?

    node.js - Heroku 和 node-cron?

    javascript - 如何将 signalmaster 集成到现有的expressjs 服务器

    javascript - 如何检索 Meteor.js 集合然后在 DOM 加载后将其传递给函数

    java - 如何使用 Scala/Java 中的索引从另一个数组分配一个数组的元素?