如何使用JavaScript迭代器遍历API对象?

3
我想通过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的过程中。

你想学习迭代器协议还是只是想让它工作?如果你使用生成器,那么它会更容易。另外,数组也是迭代器,所以你的iteratorCV是没有意义的。 - jcubic
只需使用 array[Symbol.iterator]()data.results 获取迭代器,您不需要 iteratorCV 函数。 - jcubic
嗨jcubic,我正在使用迭代器,因为每次点击我都想迭代到下一个数组元素。数组是否有隐式迭代函数?如果是的话,请详细说明或分享任何有用的链接。 - Astro
正如我所评论的,array[Symbol.iterator]()是显式迭代函数,与iteratorCV的输出相同。 - jcubic
3个回答

1

您正在调用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);

嗨Bergi,非常感谢您的回复并指出重复请求部分。但是现在,如果我尝试使用const iteratorPromise = getCV();和console.log(iteratorPromise),我会得到“未定义”的结果。因此,进一步点击会给我另一个错误。cv.js:15Uncaught TypeError:无法读取未定义的属性(读取'then'),位于HTMLButtonElement.nextCV (cv.js:15) - Astro
这很奇怪,你问题中的 getCV() 函数确实会 return 一个 Promise? - Bergi
是的,它返回一个Promise。现在我遇到了这个错误。 Uncaught TypeError: Cannot read properties of undefined (reading 'next') at HTMLButtonElement.nextCV (cv.js:27)`getCV().then(iterator => { next.addEventListener('click', function nextCV(e) { const a = iterator.next().value console.log(a); // or DOM manipulation }); })`迭代器变量被赋予了未定义的值。 :( - Astro
听起来承诺没有以迭代器作为其结果实现。你的 getCV 函数仍然从承诺链中返回 iteratorCV(data.results),对吗? - Bergi
抱歉 @Bergin,我在代码中犯了一个愚蠢的错误,数组数据实际上是 data.results。但是我将其作为对象传递了..我的输入看起来像这样.. {"results":[{"gender":"female","name":{"title":"Miss",.................}... 我已经相应地进行了更改,现在你的代码可以正常工作了。感谢你的时间。非常感激。 - Astro
我会确保下次包括输入。 - Astro

1

我试图模拟fetch Promise,我认为这就是你正在寻找的内容?当然,可以进行优化,例如避免进行相同的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>


嗨,Kanishk,感谢您的回复。您能否帮我解决如何在getCV()中使用fetch api,是否必须使用setTimeout()? - Astro
@Astro,请将我的代码片段中的getCV代码替换为您的fetch代码。如果可以,请告诉我。 - Kanishk Anand
我猜我们不能在fetch()中使用Promise关键字。Uncaught SyntaxError: Unexpected identifier。 - Astro
我在interatorCV函数的data参数中输入了错误的对象而不是数组。感谢这种方法。我对async await没有太多概念。我会尝试并让您知道这种方法是否有效。 - Astro

0

感谢各位宝贵的时间。这就是我得到最终结果的方法。希望对将来有所帮助。

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};
        }
    };
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接