计算for循环中JSON中两个值之间的百分比

Calculate percentage between two values in a JSON in a for loop

本文关键字:两个 之间 百分比 循环 for JSON 计算      更新时间:2023-09-26

我有一个JSON,里面有日常数据。

我想做的是,对于每个值,计算第n天和第n+3天之间的差异百分比。

quote1是第n天,quote2是第n+3天。

但是,由于明显的原因,我不能在for循环中使用quotes[i+3]

知道吗?非常感谢。

for (var i = quotes.length - 1; i >= 0; i--) {
  function percent(quote1, quote2) {
    var quote1 = parseInt(quote1);
    var quote2 = parseInt(quote2);
    return ((quote1 / quote2) -1 ) * 100;
  }
  console.log(percent(quotes[i].Close, quotes[i].Close) + ' %');
};

首先,将function放在for循环中并不是一个好主意:

function percent(quote1, quote2) {
  var quote1 = parseInt(quote1);
  var quote2 = parseInt(quote2);
  return ((quote1 / quote2) -1 ) * 100;
}
for (var i = quotes.length - 1; i >= 0; i--) {  
  console.log(percent(quotes[i].Close, quotes[i].Close) + ' %');
};

这是一个很好的实践,因为每次通过循环时都要定义function,这是低效的,而且几乎违背了创建function的目的,即限制冗余代码。

接下来,对于你的问题,如果你有一个3的范围,在这个范围内你总是会得到差异,你可以将你的循环偏移到i=END-3=0 上结束

for (var i = quotes.length - 1; i >= 3; i--) {  
  console.log(percent(quotes[i].Close, quotes[i-3].Close) + ' %');
};

或在i = Start + 3 = Length of List 上启动

for (var i = (quotes.length - 1) - 3; i >= 0; i--) {  
  console.log(percent(quotes[i].Close, quotes[i+3].Close) + ' %');
};

编辑

根据您向我展示的输出图像,我建议从使用parseInt切换到使用parseFloat以保留十进制值。这就是导致奇怪结果的原因。例如:

percent(29.19,28.17) => 3.57... %
percent(29.65,29.24) => 0 %

之所以会出现这种情况,是因为您正在计算输入整数值的百分比变化,而不包括有效数字所在的小数部分:

逐步通过function percent:

>>> percent("29.19","28.17");
    // Internal
    var quote1 = parseInt("29.19"); // quote1 now equals 29
    var quote2 = parseInt("28.17"); // quote2 now equals 28
    return ((quote1/quote2) - 1) * 100; 
    // ( (29/28) - 1 ) * 100
    // ( (1.0357142857142858) - 1) * 100
    // (0.0357...) * 100 = 3.57....

第二个例子:

>>> percent("29.65","29.24");
    // Internal
    var quote1 = parseInt("29.65"); // quote1 now equals 29
    var quote2 = parseInt("29.24"); // quote2 now equals 29
    return ((quote1/quote2) - 1) * 100; 
    // ( (29/29) - 1 ) * 100
    // ( (1) - 1) * 100
    // (0) * 100 = 0

切换到parseFloat,一切都应该正常。

function percent(quote1, quote2) {
  var quote1 = parseFloat(quote1);
  var quote2 = parseFloat(quote2);
  return ((quote1 / quote2) -1 ) * 100;
}

为什么不以quotes.length-4开始for循环?无论如何,你都不会得到前三句名言的有意义的答案。

for (var i = quotes.length - 4; i >= 0; i--) {
  function percent(quote1, quote2) {
    var quote1 = parseInt(quote1);
    var quote2 = parseInt(quote2);
    return ((quote1 / quote2) -1 ) * 100;
  }
  console.log(percent(quotes[i].Close, quotes[i+3].Close) + ' %');
};