我有一个包含每日数据的 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 %
发生这种情况是因为您正在计算输入整数值的百分比变化,而不包括有效数字所在的小数部分:
单步执行您的函数百分比
:
>>> 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;
}
关于javascript - 在for循环中计算JSON中两个值之间的百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23134616/