如何使用迭代器对使用JavaScript的API对象进行迭代



我想通过JavaScript迭代器对JSON对象(数组(进行迭代。我无法将从迭代器函数获取的数据存储在变量中,以便使用该变量进行DOM操作。

next.addEventListener('click',nextCV);
function nextCV(){
const a =getCV().then(data=> 
data.next().value)

}
function getCV(){


return fetch(url).then(response=>{return response.json()
}).then(data=>{


return iteratorCV(data.results)
})

}
function iteratorCV(data){
console.log('inside iterator')
let nextindex=0;
return {
next: function(){
return nextindex<data.length ? {value: data[nextindex++], done:false} : {done:true};
}
};
}

在这里,每当单击事件发生时,我想获取存储到变量"a"的下一个数组数据。请帮忙。

附言:我还在学习JavaScript。

您正在调用getCV(),它会重复请求,并在每次单击元素时创建一个新的迭代器。听起来你真正想做的是

const iteratorPromise = getCV();
iteratorPromise.catch(console.error);
next.addEventListener('click', function nextCV(e) {
iteratorPromise.then(iterator => {
const a = iterator.next().value;
console.log(a); // or DOM manipulation
});
});

getCV().then(iterator => {
next.addEventListener('click', function nextCV(e) {
const a = iterator.next().value
console.log(a); // or DOM manipulation
});
}).catch(console.error);

我试着模拟fetchPromise,我想这就是你想要的?当然,也可以进行优化,比如避免进行相同的API调用,并根据用例返回cached结果。

const btn = document.querySelector('button');
btn.addEventListener('click',nextCV);
async function nextCV(){
let it = await getCV();
let result = it.next();
const a = [];
while(!result.done) {
a.push(result.value)
result = it.next();
}
// Result stores in 'a'. Do DOM manipulation from here
console.log('final result', a);


}
function getCV(){
return new Promise((resolve) => {
setTimeout(() => {
resolve(iteratorCV([1,2,3,4,5]))
}, 1000)
})
}
function iteratorCV(data){
console.log('inside iterator')
let nextindex=0;
return {
next: function(){
return nextindex<data.length ? {value: data[nextindex++], done:false} : {done:true};
}
};
}
<button> Click </button>

感谢大家抽出宝贵时间。以下是我的期末考试。希望这对将来的人有所帮助。

const url="https://.......";
//adding button for the iteration
const next = document.getElementById('next');

//for Dom manipulation
let image=document.getElementById('image');
let profile=document.getElementById('profile');

getCV().then(iterator => {
next.addEventListener('click', function nextCV(e) {

const a = iterator.next().value
console.log(a);
//now you can use the variable for DOM manipulation 
image.innerHTML=       });
})
//get api
function getCV(){


return fetch(url).then(response=>{ 
return response.json()
}).then(data=>{


console.log(data.results)
return iteratorCV(data.results);

})

}

//Iterating over the FETCHED DATA one by one data

function iteratorCV(data){
console.log('inside iterator')
// console.log(data)
let nextindex=0;
return {
next: function(){
return nextindex<data.length ? {value: data[nextindex++], done:false} : {done:true};
}
};
}

最新更新