首页 > 解决方案 > 获取随机 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并输出到控制台?

标签: javascriptarraysjsonasynchronousfetch

解决方案


在您的代码中,您假设远程获取操作将始终在 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)
}


推荐阅读