【问题标题】:How to iterate using iterator over API object using JavaScript?如何使用迭代器在 API 对象上使用 JavaScript 进行迭代?
【发布时间】:2022-01-19 06:21:42
【问题描述】:

我想通过 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 毫无意义。
  • 只需使用array[Symbol.iterator]()data.results 获取迭代器即可,不需要iteratorCV 函数。
  • 您好 jcubic,我正在使用迭代器,因为每次单击我想迭代到下一个数组元素。数组是否具有隐式迭代功能?如果有,请详细说明或分享任何有用的链接。跨度>
  • 正如我所评论的,array[Symbol.iterator]() 是显式迭代函数,与 iteratorCV 的输出相同。

标签: javascript dom-events javascript-objects fetch-api


【解决方案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)。所以进一步点击点击会给我另一个error.cv.js:15 Uncaught TypeError: Cannot read properties of undefined (reading 'then') at HTMLButtonElement.nextCV (cv.js:15)跨度>
  • 嗯,这很奇怪,您问题中的 getCV() 函数是否对 return 做出了承诺?
  • 是的,它正在返回一个承诺。现在我收到了这个错误。未捕获的类型错误:无法在 HTMLButtonElement.nextCV (cv.js:27)getCV().then(iterator =&gt; { next.addEventListener('click', function nextCV(e) { const a = iterator.next().value console.log(a); // or DOM manipulation }); }) 处读取未定义的属性(读取“下一个”),迭代器变量被分配为未定义。 :(
  • 听起来诺言并没有以迭代器作为其结果。你的getCV 函数仍然是来自承诺链的return iteratorCV(data.results),对吧?
  • 对不起@Bergin 我在代码中犯了一个愚蠢的错误,数组数据实际上是data.results。但我将它作为一个对象传递..我的输入看起来像.. {"results":[{"gender":"female","name":{"title":"Miss",..... ....}......我已经做出相应的更改,现在您的代码运行良好。感谢您的时间。非常感谢
【解决方案2】:

我试图模拟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};
        }
    };
}
&lt;button&gt; Click &lt;/button&gt;

【讨论】:

  • 您好 Kanishk,感谢您的回复。你能帮我看看如何在 getCV() 中使用 fetch api,是否有必要使用 setTimeout()?
  • @Astro 只需将 getCV 中的代码从我的 sn-p 替换为您的 fetch 代码。让我知道这是否有效。
  • 我猜我们不能在 fetch() 中使用 Promise 关键字。Uncaught SyntaxError: Unexpected identifier
  • 我在 interatorCV 函数中向数据参数提供了错误的输入(对象而不是数组)。感谢您的这种方法。我对异步等待没有太多概念。我会尝试让您知道是否这样方法也有效。
【解决方案3】:

感谢大家宝贵的时间。这是我的最终结果。希望这对将来的人有所帮助。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-27
    • 2018-03-19
    • 2014-09-03
    • 2012-06-18
    • 2012-02-24
    • 1970-01-01
    • 2011-11-22
    相关资源
    最近更新 更多