我试图迭代一个对象的嵌套子元素,但是在每个孩子之后需要延迟。通常我会编写一个递归函数并使用它来迭代一个对象,但这会立即发生。我怎么能拖延呢?
我考虑过将索引保存在变量中并使用它来访问子项,然后每次运行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
}
]
}
]
答案 0 :(得分:0)
首先从层次结构中创建一个平面数组:
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>