javascript - 获取随机 img url,然后附加到数组
问题描述
下面我在获取图像后无法将图像附加到数组中。我有一个定义为的数组totalMemes
,当它遍历所有 url 时,我想追加到totalMemes
数组中。但是,然后我想在totalMemes
数组中选择一个随机 url 并将一个随机图像从它记录到控制台。
我下面的代码要么将数组返回为空白、未定义,要么抛出 .push 不是函数的错误。基本上无法访问数组,尤其是在获取 json 文件中的所有 url 之后。如果我想要console.log
每个链接,一切仍然有效,但我想最终记录一个随机链接。
totalMemes = []
fetch(`https://www.reddit.com/r/dankmemes/new.json?sort=hot`)
.then(res => res.json())
.then(res => res.data.children)
.then(res => res.map(post => ({
author: post.data.author,
link: post.data.url,
img: post.data.preview.images[0].source.url,
})))
.then(res => res.map(render))
.then(res => console.log(res))
const render = post => {
totalMemes.push(post.img)
}
setTimeout(() => {
singleMeme = totalMemes[Math.floor(Math.random() * totalMemes.length)];
console.log(singleMeme)
}, 900)
如何遍历 json 文件中的所有图像 url,并将每次迭代附加到总数组中。然后从数组中找到一个随机的图像url并输出到控制台?
解决方案
在您的代码中,您假设远程获取操作将始终在 900 毫秒内完成。然后您尝试在此间隔之后处理数据。当您尝试处理数据时,很可能没有响应。
而不是猜测响应到达时间和延迟数据处理,您需要在收到数据后进行数据处理。换句话说,你应该用另一种.then
方法来做。
.then(() => {
singleMeme = totalMemes[Math.floor(Math.random() * totalMemes.length)];
console.log(singleMeme)
})
这是一个运行代码:
totalMemes = []
fetch(`https://www.reddit.com/r/dankmemes/new.json?sort=hot`)
.then(res => res.json())
.then(res => res.data.children)
.then(res => res.map(post => ({
author: post.data.author,
link: post.data.url,
img: post.data.preview.images[0].source.url,
})))
.then(res => res.map(render))
.then(() => {
singleMeme = totalMemes[Math.floor(Math.random() * totalMemes.length)];
console.log(singleMeme)
})
const render = post => {
totalMemes.push(post.img)
}
推荐阅读
- json - 将 JsonArray 值分配给匹配案例类的变量
- c++ - 如何使用 Visual Studio 2008 将字符串映射到函数?
- python - Drive API v3 - Getting all files inside a particular folder
- docker - 运行 Docker 映像的问题
- php - How to get comments within an HTML element by XPath?
- python - converting complex ffmpeg command to python3
- c# - 如何在 bot framework v4 中调用中间件 OnMessageActivityAsync?
- sql-server - Compute data between First and Last Day Of Last Month
- google-cloud-platform - 我未能在 googlecloudrobotics/core 的“从源代码部署 Cloud Robotics Core”页面中的步骤中“构建”
- excel - 在活动工作表 VBA 之后从多个工作表复制特定列