gpt4 book ai didi

javascript - 延迟迭代对象

转载 作者:行者123 更新时间:2023-11-28 07:32:48 24 4
gpt4 key购买 nike

我正在尝试迭代对象的嵌套子对象,但需要在每个子对象之后有一个延迟。通常我只会编写一个递归函数并使用它来迭代一个对象,但这几乎是立即发生的。我怎样才能延迟执行此操作?

我考虑过将索引保存在变量中并使用它访问子项,然后每次运行 setInterval 时增加索引,但是如何扩展它以考虑嵌套?

迭代函数:

function iter(obj) {
for (var i = 0; i < obj.length; i++) {
console.log(obj[i].command);
if (typeof obj[i].contains == "object") {
iter(obj[i].contains);
}
}
}
iter(object);

示例对象:

[
{
"command":"do (5)",
"contains":[
{
"command":"move.up()",
"contains":false
},
{
"command":"move.left()",
"contains":false
},
{
"command":"if (kind == \"item\")",
"contains":[
{
"command":"move.down()",
"contains":false
}
]
},
{
"command":"move.right()",
"contains":false
}
]
}
]

最佳答案

首先从层次结构创建一个平面数组:

function iter(obj) {
var result = [];
for (var i = 0; i < obj.length; i++) {
result.push(obj[i]);
if (typeof obj[i].contains == "object") {
result = result.concat(iter(obj[i].contains));
}
}
return result;
}

var items = iter(object);

现在您可以使用计时器和索引迭代数组:

var index = 0;
var timer = window.setInterval(function(){
if (index < items.length) {
console.log(items[index].command);
index++;
} else {
window.clearInterval(timer);
}
}, 1000);

演示:

var object = [
{
"command":"do (5)",
"contains":[
{
"command":"move.up()",
"contains":false
},
{
"command":"move.left()",
"contains":false
},
{
"command":"if (kind == \"item\")",
"contains":[
{
"command":"move.down()",
"contains":false
}
]
},
{
"command":"move.right()",
"contains":false
}
]
}
];

function iter(obj) {
var result = [];
for (var i = 0; i < obj.length; i++) {
result.push(obj[i]);
if (typeof obj[i].contains == "object") {
result = result.concat(iter(obj[i].contains));
}
}
return result;
}

var items = iter(object);

var index = 0;
var timer = window.setInterval(function(){
if (index < items.length) {
log(items[index].command);
index++;
} else {
window.clearInterval(timer);
}
}, 1000);

function log(str) {
document.getElementById('log').innerHTML += str + '<br>';
}
<div id="log"></div>

关于javascript - 延迟迭代对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28933700/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com