清理Javascript中的多个变量

时间:2018-08-13 16:49:56

标签: javascript variables declaration

我想清理变量声明,并想知道是否有更好的方法来解决它。

下面,我有一个基于数组长度创建图表数据的函数。我在将值添加到它们之前声明每个数组。我有4个不同的区域(pa1-4)和6个不同的状态。我为每个区域的每个状态声明一个变量,以及总计的一个变量。

function jobcharts(data) {

//declaring each variable
var i;
var pa1Sum = [],
    pa1SumComplete = [],
    pa1SumGenSM = [],
    pa1SumQue = [],
    pa1SumInP = [],
    pa1SumFin = [],
    pa1SumOH = [],
    pa2Sum = [],
    pa2SumComplete = [],
    pa2SumGenSM = [],
    pa2SumQue = [],
    pa2SumInP = [],
    pa2SumFin = [],
    pa2SumOH = [](...etc);

//going through all data
for (i = 0; i < data.features.length; i++) {
    var jobArea = data.features[i].properties.JOB;

    if (data.features[i].properties.PRIORITY_AREA === "PA1") {
        pa1Sum.push(data.features[i]);
        if (data.features[i].properties["JOB STATUS"] === "ON HOLD") {
            pa1SumOH.push(data.features[i].properties.JOB);
        } else if (data.features[i].properties["JOB STATUS"] === "Generating SM") {
            pa1SumGenSM.push(data.features[i].properties.JOB);
        } else if (data.features[i].properties["JOB STATUS"] === "Queued") {
            pa1SumQue.push(data.features[i].properties.JOB);
        } else if (data.features[i].properties["JOB STATUS"] === "In Progress") {
            pa1SumInP.push(data.features[i].properties.JOB);
        } else if (data.features[i].properties["JOB STATUS"] === "Final Review") {
            pa1SumFin.push(data.features[i].properties.JOB);
        } else {
            pa1SumComplete.push(data.features[i].properties.JOB);
        } (...etc);

然后我得到循环完成后的长度,并根据需要构造数据。

function arraytest(array, total) {
    if (array.length > 0) {
        return (Math.round(((array.length) / total.length) * 100));
    } else {
        return "0";
    }
}

var pa1Arr = [arraytest(pa1SumComplete, pa1Sum), arraytest(pa1SumFin, pa1Sum), arraytest(pa1SumInP, pa1Sum), arraytest(pa1SumQue, pa1Sum), arraytest(pa1SumGenSM, pa1Sum), arraytest(pa1SumOH, pa1Sum)];

有没有更好的方法来构造变量,因此我的函数开头没有24个声明?

1 个答案:

答案 0 :(得分:0)

是的,只需获取工作状态并按此分组:

  const totals = {};
  let count = 0;

   for(const { properties: { ["JOB STATUS"]: status, JOB: job, PRIORITY_AREA: priority } } of data.features) {
     if(priority === "Pa1") {
        count++;
        if(!totals[status])
          totals[status] = [];
        totals[status].push(job);
     }
  }

现在要获取百分比可以映射对象值:

 Object.values(totals).map(entries => entries.length / count * 100);