首页 > 解决方案 > 清理 Javascript 中的多个变量

问题描述

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

下面我有一个基于数组长度创建图表数据的函数。我在向它们添加值之前声明每个数组。我有 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 个声明?

标签: javascriptvariablesdeclaration

解决方案


是的,只需按照工作状态和分组:

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

推荐阅读