JavaScript,JSON:如何在特定时间内运行 for 循环?
Posted
技术标签:
【中文标题】JavaScript,JSON:如何在特定时间内运行 for 循环?【英文标题】:JavaScript, JSON : how can I run a foor loop a specific amount of time? 【发布时间】:2022-01-17 08:15:33 【问题描述】:我有这个代码 - 它有点棘手:
let i = 0;
const inputBuffer = [];
const randomnumber = (min, max) =>
return Math.floor(Math.random() * (max - min + 1) + min);
for (let k = 0; k < 10; k++)
console.log(convert(randomnumber(0, 1982)));
function convert(input)
inputBuffer.push(input);
const output = "current" : "0";
if (i % 3 == 0)
let sum = 0;
for (let ii = 0; ii < i; ii++)
sum += inputBuffer[ii];
output.sum = sum;
i++;
output.current = input;
return JSON.stringify(output);
输出如下:
"current":605,"sum":0
"current":708
"current":456
"current":1838,"sum":1769
"current":1619
"current":1404
"current":1068,"sum":6630
"current":1178
"current":989
"current":1280,"sum":9865
但我希望它看起来像这样:
"current": 605
"current": 708
"current": 456
"current": 1838,"sum":1769
"current": 1619
"current": 1404
"current": 1068,"sum":6630
"current": 1178
"current": 989
"current": 1280,"sum":9865
let i = 0;
const inputBuffer = [];
const randomnumber = (min, max) =>
return Math.floor(Math.random() * (max - min + 1) + min);
for (let k = 0; k < 10; k++)
console.log(convert(randomnumber(0, 1982)));
function convert(input)
inputBuffer.push(input);
const output =
"current": "0"
;
if (i % 3 == 0)
let sum = 0;
for (let ii = 0; ii < i; ii++)
sum += inputBuffer[ii];
output.sum = sum;
i++;
output.current = input;
return JSON.stringify(output);
我不想第一次显示总和,但以后每 3 次显示一次
有什么想法吗? :D
PS。我更喜欢保持基本,只使用 for 循环
祝你有个愉快的夜晚
【问题讨论】:
【参考方案1】:您可以在分配output.sum
的值时检查i
是否不为零吗?
类似于以下内容:
let i = 0;
const inputBuffer = [];
const randomnumber = (min, max) =>
return Math.floor(Math.random() * (max - min + 1) + min);
for (let k = 0; k < 10; k++)
console.log(convert(randomnumber(0, 1982)));
function convert(input)
inputBuffer.push(input);
const output = "current" : "0";
if (i % 3 == 0)
let sum = 0;
for (let ii = 0; ii < i; ii++)
sum += inputBuffer[ii];
if (i !== 0) output.sum = sum; // HERE
i++;
output.current = input;
return JSON.stringify(output);
【讨论】:
是的,就是这样,我也用 debounce 做到了,谢谢:D【参考方案2】:我发现了这一点,你的显然更短,但这是我的想法:D
let i = 0;
const inputBuffer = [];
let db = false;
const randomnumber = (min, max) =>
return Math.floor(Math.random() * (max - min + 1) + min);
for (let k = 0; k < 10; k++)
console.log(convert(randomnumber(0, 1982)));
function convert(input)
inputBuffer.push(input);
const output = "current" : "0";
if (db && i % 3 == 0)
let sum = 0;
for (let ii = 0; ii < i; ii++)
sum += inputBuffer[ii];
output.sum = sum;
i++
db = true;
output.current = input;
return JSON.stringify(output);
【讨论】:
以上是关于JavaScript,JSON:如何在特定时间内运行 for 循环?的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 package.json 脚本复制具有特定文件扩展名的文件
如何使用Javascript读取json文件并将特定键的值写入同一json文件中?