javascript - 为什么在 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)
...
});
}
但是数组的所有项目都是相同的,应该是不同的......为什么?我如何解决这个问题?
谢谢
解决方案
推荐阅读
- java - 当 csv 值不存在时,如何让 if 语句正常工作?
- android - 在 Android 中处理不同的日期格式
- c - 下面给出的代码是错误的吗?
- javascript - 如何在javascript中使用带有railsasset_path的动态值?
- python - 无法使用 pd.to datetime() 正确格式化日期时间中的数据框列
- c# - 如何使数据网格中的列成为复选框?
- python - “ImportError: Failed to load GLFW3 shared library”在 Linux 上没有 root 访问权限
- awk - 为什么双引号 awk 命令替换在 csh 中失败
- sql-server - char(5) 和 int(5) 的区别
- mediawiki - 使用 Wikimedia API 获取位置