使用javascript反转数组并填补空白

时间:2015-09-24 09:19:49

标签: javascript arrays

因此,我们有一组数据,这些数据的百分比值递增,但缺少一些空白。

所以例如

  {
    "months": 11,
    "factor": 1.31,
    "upperMonths": 10.5,
    "lowerMonths": 11.49,
    "limit": 20,
    "percentage": 8
  },
  {
    "months": 10,
    "factor": 1.3,
    "upperMonths": 9.5,
    "lowerMonths": 10.49,
    "limit": 20,
    "percentage": 9
  },
  {
    "months": 8,
    "factor": 1.28,
    "upperMonths": 7.5,
    "lowerMonths": 8.49,
    "limit": 20,
    "percentage": 10
  },
  {
    "months": 7,
    "factor": 1.27,
    "upperMonths": 6.5,
    "lowerMonths": 7.49,
    "limit": 20,
    "percentage": 12
  }

请注意,缺少百分比11 ......

所以我们有一个函数,它基本上循环遍历数组并使用上面对象的数据填充任何缺失的百分比,因此百分比11将数据从百分比10挖出来作为副本。

http://jsfiddle.net/guideveloper/xnaqtq9y/11/

我们的问题是我们需要反转数组并执行相同操作,所以现在百分比12将是第一个对象,然后它将循环遍历数组并反向填充空白,因此我们的最终对象将是< / p>

  {
    "months": 7,
    "factor": 1.27,
    "upperMonths": 6.5,
    "lowerMonths": 7.49,
    "limit": 20,
    "percentage": 12
  },
  {
    "months": 7,
    "factor": 1.27,
    "upperMonths": 6.5,
    "lowerMonths": 7.49,
    "limit": 20,
    "percentage": 11
  },
  {
    "months": 8,
    "factor": 1.28,
    "upperMonths": 7.5,
    "lowerMonths": 8.49,
    "limit": 20,
    "percentage": 10
  },
  {
    "months": 10,
    "factor": 1.3,
    "upperMonths": 9.5,
    "lowerMonths": 10.49,
    "limit": 20,
    "percentage": 9
  },
  {
    "months": 11,
    "factor": 1.31,
    "upperMonths": 10.5,
    "lowerMonths": 11.49,
    "limit": 20,
    "percentage": 8
  }

然后我们需要再次撤回它。

任何想法??

3 个答案:

答案 0 :(得分:0)

只需使用reverse反转数组两次:

test.reverse()

答案 1 :(得分:0)

您可以使用lodashhttps://lodash.com/docs#prototype-reverse)或undercore.js等javascript库,也可以使用原生reverse功能。

答案 2 :(得分:0)

好的所以我们让它完全按照我们想要的方式工作,并且这里有一个更新的小提琴

http://jsfiddle.net/guideveloper/whasgrfL/7/

function fillArray(arr) {
    var i = 1;
    while (i < test.length) {
        if ((test[i]["percentage"] * 1 - test[i - 1]["percentage"] * 1) > 1) {
            test.splice(i, 0, { 
              "percentage": test[i-1].percentage+1,
              "factor": test[i]["factor"],
              "upperMonths": test[i]["upperMonths"],
              "lowerMonths": test[i]["lowerMonths"],
              "limit": test[i]["limit"],
               "months": test[i]["months"] });
        }
        i++;
    }
    return test;
}