简体   繁体   中英

can't iterate over an array in java script

iam traying to iterate over an array in js but it's not work and and i always get length equal 0 and when i try to access elements by index i get undefined but when i try to print my array by clg it worked well here is my code


function getData(url) {
    let arr = []
    fetch(url).then(response => response.json()).then(data => {
        for (let index = 0; index < data.length; index++) {
            arr[index] = data[index].content
        }
    })
        console.log(arr)
}

with console.log (arr) this the result

[]
0: "any"
1: "any"
2: "any"
3: "any"
length: 4
[[Prototype]]: Array(0)

but with console.log (arr[0]) i got

undefined

i want to get result from fetch and convert it to array and iterate over this array

You should return the Promise and the arr too. Then in a .then set the referenc you want.

function getData(url) {
  return fetch(url).then(response => response.json()).then(data => {
    let arr = [];
    for (let index = 0; index < data.length; index++) {
      arr[index] = data[index].content
    }
    return arr;
  })
}

getData(url).then(contents => { /*... do whatever you want */ });

You can use async/await , so itt will be easier to manage callbacks

async function getData(url) {
  return fetch(url).then(response => response.json()).then(data => data.map(d => d.content));
}

const contents = await getData(url);
for(const content of contents){
 /*... do whatever you want */ 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM