首页 > 解决方案 > 为什么在 for 循环中获取 url 总是返回相同的元素

问题描述

https://source.unsplash.com/featured/?nature,animal,street,world每次在浏览器上调用此 url 时,我都有以下 url ,它返回不同的图像。是的,我需要调用它几次来填充数组,然后我使用 for 循环,但是它将相同的图像返回到数组的每个 idx ......这是我用来填充数组元素的函数:

async function getPhotos() {
    
    try {
        for (let i = 0; i < 10; i++) {
            let response = await fetch(apiUrl);
            photosArray.push(response);
        }

        console.log('length: ', photosArray.length);

        displayPhotos();//function that use each array elements to show a diffent img on screen
    } catch (error) {
        console.log(error);
    }
}

基本上displayPhotos()看起来像

function displayPhotos() {
    ...

    /* Run function for each object in photosArray */
    photosArray.forEach((photo) => {
        /* Create <img> for photo */
        const img = document.createElement('img');
        img.setAttribute('src', photo.url); //retrive img url inside response (item of array)


        ...
    });
}

但是数组的所有项目都是相同的,应该是不同的......为什么?我如何解决这个问题?

谢谢

标签: javascriptrestfetch

解决方案


推荐阅读