簡體   English   中英

javascript 將數據存儲在全局變量數組中(或其他更好的方式)

[英]javascript store data in global variable array(or other better ways)

在 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 有時被傳遞給 function,有時作為全局數組訪問。

我在網上看到說應該避免使用全局變量。 但在這種情況下,我不確定我應該遵循什么規則或示例來改進代碼,使其不易出現問題。

歡迎任何建議。 提前致謝。

沒有必要為此使用全局變量,因為您已經混合了全局變量和局部變量。 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());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM